Java 将数组增加 X 大小 [英] Java increase array by X size
问题描述
我需要一个数组,我可以从一开始就确定它的大小,如果它没有更多的空格,则通过 X
增加它的大小.例如:
I need an array that I can determine its size from the start and if it has no more empty spaces then increase its size by X
. For example:
int arraySize = 2;
int[] intArray = new int[arraySize];
int counter = 0;
while(something){
if(counter == arraySize){
// increase array size by X
}
intArray[counter] = counter;
counter++;
}
我检查了 ArrayList
和 Vector
但我没有找到方法.
I checked ArrayList
and Vector
but I did not find a way.
推荐答案
我认为 ArrayList
在这种情况下比简单的数组更好,因为它会自动增长.来自 javadoc:
I think ArrayList
is better in this case instead of simple arrays because automatically grows. From the javadoc:
每个 ArrayList 实例都有一个容量.容量是大小用于存储列表中元素的数组.它总是在至少与列表大小一样大.当元素被添加到一个ArrayList,它的容量会自动增长.成长的细节除了添加元素具有固定摊销时间成本.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
但是如果你必须使用数组,数组 实用程序类为您提供帮助
But if you have to use arrays, Arrays utility class comes to your aid
intArray = Arrays.copyOf(intArray, intArray.length + x);
这篇关于Java 将数组增加 X 大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!