java给数组添加元素代码
时间: 2023-10-03 12:08:26 浏览: 93
可以使用ArrayList类进行添加元素,例如:
```
ArrayList<String> list = new ArrayList<>();
list.add("element");
```
也可以使用System.arraycopy方法进行添加元素,例如:
```
String[] arr = new String[] {"element1"};
String[] newArr = new String[arr.length + 1];
System.arraycopy(arr, 0, newArr, 0, arr.length);
newArr[arr.length] = "element2";
arr = newArr;
```
相关问题
java int数组添加元素
Java中的数组长度是固定的,无法直接添加元素。但可以通过创建一个新的数组,将原数组中的元素复制到新数组中,并在新数组中添加新元素来实现“添加”元素的效果。
下面是一个示例代码,演示了如何将一个整型数组 arr 中的元素复制到新数组 newArr 中,并在末尾添加一个新元素:
```
int[] arr = {1, 2, 3, 4, 5};
int[] newArr = new int[arr.length + 1];
System.arraycopy(arr, 0, newArr, 0, arr.length);
newArr[arr.length] = 6; // 在新数组的末尾添加新元素 6
```
这里使用了 `System.arraycopy()` 方法来将原数组中的元素复制到新数组中。该方法的参数依次为原数组、原数组的起始位置、新数组、新数组的起始位置和要复制的元素个数。最后,在新数组的末尾添加了一个新元素。
javastring数组添加元素
在 Java 中,数组的长度是固定的,不能直接添加或删除元素。但是,我们可以创建一个新的数组,将原数组中的元素拷贝到新数组中,并在新数组的末尾添加新的元素。
下面是一个示例代码,演示如何向一个 String 类型的数组中添加元素:
```java
// 原数组
String[] originalArray = {"apple", "banana", "orange"};
// 新数组的长度比原数组多1
String[] newArray = new String[originalArray.length + 1];
// 将原数组中的元素拷贝到新数组中
for (int i = 0; i < originalArray.length; i++) {
newArray[i] = originalArray[i];
}
// 在新数组的末尾添加新元素
newArray[newArray.length - 1] = "pear";
// 输出新数组
System.out.println(Arrays.toString(newArray));
```
输出结果为:`[apple, banana, orange, pear]`
阅读全文
相关推荐
















