why arrays are initialized to default values but not arraylist in java?

arraylist, arrays, java, list

Solution

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.

Problem

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; ```

Original source