Java将数组增加X大小 [英] Java increase array by X size

查看:76
本文介绍了Java将数组增加X大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个可以从一开始就确定其大小的数组,如果它没有更多的空格,则将其大小增加 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆