Java将元素追加到原始数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25513833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java append element to primitive array
提问by Pratik Khadloya
Is it possible to append elements at the end of a primitive array in Java?
For ex: if int[] a = new int[10];
is an array. How can i go on appending elements at the end?
是否可以在 Java 中的原始数组末尾附加元素?例如:ifint[] a = new int[10];
是一个数组。我怎样才能在最后追加元素?
Edit:
I do not want to use ArrayList for performance reason and want to stay with primitive arrays.
编辑:
出于性能原因,我不想使用 ArrayList 并希望保留原始数组。
回答by azurefrog
Once created, the size of an array in Java is fixed.
创建后,Java 中数组的大小是固定的。
If you want to have a dynamically sized storage, you will want to use an ArrayList
.
如果您想拥有动态大小的存储,您将需要使用ArrayList
.
The alternative is to create a new (larger) array and copy the contents of the old one, but keep in mind that this will be very expensive in both time and memory:
另一种方法是创建一个新的(更大的)数组并复制旧数组的内容,但请记住,这在时间和内存方面都非常昂贵:
// this is a terrible idea, don't do it
public int[] append(int[] i, int newElement) {
int[] copy = new int[i.length+1];
System.arraycopy(i, 0, copy, 0, i.length);
copy[i.length]= newElement;
return copy;
}
This is effectively what an ArrayList
is doing for you behind the scenes (albeit more efficiently), so if you're going to be adding very many elements, you'll want to start with a larger ArrayList
than the default capacity of 10 elements.
这实际上是 anArrayList
在幕后为您做的事情(尽管效率更高),因此如果您要添加非常多的元素,您需要从大于ArrayList
默认容量 10 个元素的容量开始。
回答by qbit
A way to make an Array
more dynamic is to create a method that creates a new longer array and replace the old one with it.
一种Array
更动态的方法是创建一个方法来创建一个新的更长的数组并用它替换旧的数组。
For example.
例如。
lets say you have an int[]
of size 10 and it holds numbers 0 to 9:
假设你有一个int[]
大小为 10 的,它包含数字 0 到 9:
int[] array = new int[10];
for(int i = 0; i < array.length; i++)
array[i] = i;
Printing the contents of the array will output: 0 1 2 3 4 5 6 7 8 9
打印数组的内容将输出: 0 1 2 3 4 5 6 7 8 9
Now you can have a method like this:
现在你可以有一个这样的方法:
private int[] appendArray(int[] array, int x){
int[] result = new int[array.length + 1];
for(int i = 0; i < array.length; i++)
result[i] = array[i];
result[result.length - 1] = x;
return result;
}
and do the following
并执行以下操作
array = appendArray(array, 10);
array = appendArray(array, 10);
Now printing the contents of the array will output:
0 1 2 3 4 5 6 7 8 9 10
现在打印数组的内容将输出:
0 1 2 3 4 5 6 7 8 9 10
Alternatively you can use an ArrayList
that is basically doing a similar thing.
或者,您可以使用ArrayList
基本上做类似事情的一个。