如何在数组末尾添加元素? [英] How to add an element at the end of an array?
问题描述
我想知道如何在数组末尾添加或添加新元素。有没有简单的方法可以在最后添加元素?我知道如何使用StringBuffer,但不知道如何使用StringBuffer在数组中添加元素。我更喜欢它没有ArrayList或列表。我不知道StringBuffer是否适用于整数。
I want to know how to add or append a new element to the end of an array. Is any simple way to add the element at the end? I know how to use a StringBuffer but I don't know how to use it to add an element in an array. I prefer it without an ArrayList or list. I wonder if the StringBuffer will work on integers.
推荐答案
由于Java中的数组是固定长度的,因此无法向数组中添加元素。但是,您可以使用 Arrays.copyOf(array,size)
:
You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size)
:
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
System.out.println(Arrays.toString(array));
array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
array[array.length - 1] = 4;
System.out.println(Arrays.toString(array));
}
我仍然建议删除使用数组并使用 List
。
I would still recommend to drop working with an array and use a List
.
这篇关于如何在数组末尾添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!