Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 557
brain storm Avatar asked Jan 29 '14 23:01

brain storm


2 Answers

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.

like image 138
Greg Hewgill Avatar answered Nov 15 '22 07:11

Greg Hewgill


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, ArrayLists 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.

like image 34
tbodt Avatar answered Nov 15 '22 08:11

tbodt