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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With