Java – is there any way to set the size of ArrayList after declaration?

For example, in a traditional array, I will declare an array like this:

int array[];

Well, I'll initialize it later like this

array = new int[1000];

In ArrayList, I try to do the same, but I can only initialize it and declare it as follows

ArrayList<String> array = new ArrayList<>(1000);

It's almost the same

int[] array = new int[10000];

So I wonder if there is a way to declare an ArrayList in a separate statement and initialize it to 1000

Solution

You can use ensueacapacity (int)

ArrayList<Integer> al = new ArrayList<>();

al.ensureCapacity(1000);

It is worth noting that the array list will dynamically resize itself

You can also do this:

ArrayList<Integer> al;

al = new ArrayList<Integer>(1000);

This is more similar to regular array initialization

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>