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;
toString()method usessizeto determine how many elements print, not capacity of array. When you createArrayListwith initial capacity10its size is still0because you didn't add any elements to it yet, even if array which stores your objects was initialized as new Object[10] which means it is filled with 10 nulls.ArrayListwith is just a hint, anyway. If you specify the capacity as 10 you can still add 11 elements to it. The results of your program should be the same no matter what capacity you specify; only the performance is affected.