Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way of setting the size of an arraylist after declaring it?

For example, in a traditional array, i would declare an array like this:

int array[];

then, i would later initialize it like this

array = new int[1000];

in an arraylist i am trying to do the same but I have only been able to initialize it while declaring it like below.

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

it's almost the same as

int[] array = new int[10000];

So I would like to know if there's a way to initialize an arraylist to for example 1000 after it's been declared in a separate statement.

like image 731
answerSeeker Avatar asked Mar 21 '23 21:03

answerSeeker


2 Answers

You can use ensureCapacity(int)

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

al.ensureCapacity(1000);

It is important to note that array lists WILL dynamically resize themselves though.

So I would like to know if there's a way to initialize an arraylist to for example 1000 after it's been declared in a separate statement.

You could always do this, too:

ArrayList<Integer> al;

al = new ArrayList<Integer>(1000);

This is more akin to the regular array initialisation.

like image 94
azz Avatar answered Apr 06 '23 04:04

azz


it is not same as declaring size for array, it is initial size you are passing in

you can still go beyond 1000 runtime in case of List and not in array

ArrayList dynamically will grow the size as required, 1000 here is initial size of array wrapped under ArrayList

like image 39
jmj Avatar answered Apr 06 '23 02:04

jmj