如何在数组末尾添加元素? [英] How to add an element at the end of an array?
问题描述
我想知道如何在数组末尾添加或追加新元素.有什么简单的方法可以在最后添加元素?我知道如何使用 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));
}
我仍然建议放弃使用数组并使用 列表
.
I would still recommend to drop working with an array and use a List
.
这篇关于如何在数组末尾添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!