why arrays are initialized to default values but not arraylist in java?
Solution 1
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.
Solution 2
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.
Solution 3
You could do it like this:
List<Integer> items = Arrays.asList(new Integer[10]);
And you would get a list with 10 null elements.
Similarly,
Integer[] numbers = new Integer[10];
Arrays.fill(numbers,0);
List<Integer> list = Arrays.asList(numbers);
And you get a list with 10 elements initialised to 0;
Solution 4
The reason of null
and 0
is difference between primitive and Object
types. Their default values are null
and 0
(only false
for boolean) correspondingly.
See The Java Tutorial
ArrayList
is not physically empty after creating. It has initial capacity, but it shows his size 0
even you initialized it exactly.Because Collection size()
has logical meaning, not phisical.
List<Integer> list = new ArrayList<Integer>(10);
Also you can fill new Collection (List) with the following static method
Collections.fill(list, 0) // int 0 is auto-boxed to `Integers` 0
Solution 5
As an ArrayList doesn't initially contain any elements, it can't default the value of those elements to null or any other value.
brain storm
Updated on June 29, 2022Comments
-
brain storm almost 2 years
The implementation of
ArrayList
usesArray
under the hood. However,Arrays
are intialized to default values(0 or null)
butArrayList
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 throwingNoSuchElementException
and then I realized that it is not defaulted, where asArrays
doif (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;