The implementation of ArrayList
uses Array
under the hood. However, Arrays
are intialized to default values (0 or null)
but ArrayList
are just empty. why is this?
int[] arr = new int[10];
String[] arr1 = new String[11];
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(arr1));
List<Integer> list = new ArrayList<Integer>(10);
System.out.println(list);
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[null, null, null, null, null, null, null, null, null, null, null]
[]
This means every time I use, ArrayList
, I need to fill stuff in;
I was trying the below part in my code and it was throwing NoSuchElementException
and then I realized that it is not defaulted, where as Arrays
do
if (list.get(i)==null){
list.add(i,x);
else:
list.add(i,list.get(i)+x)
EDIT:
even List<Integer> list = new ArrayList<Integer>(10);
prints [] although I initialized the size;
When constructing an array, the number is the actual size of the array (and you can't change it later). The number in the ArrayList
constructor is the initial capacity (space reserved for elements) but the size is zero. The size of an ArrayList
can change after it is constructed.
When you create an array, you specify the size. This is required because the size of arrays can't be changed after they are created. Something must go in each element of the array, then, and the most obvious thing to put is 0
or null
.
On the other hand, ArrayList
s are designed to be able to be resized. So you shouldn't have to specify the size when you create them. If the starting size is more then zero, it would have to initialize all those elements, and it's easier not to. So the starting size is zero.
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