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

The implementation ArrayListuses Arrayunder the hood. However, Arraysinitialized to default values (0 or null), but ArrayListjust 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 that every time I use ArrayList, I need to fill in the material; I tried the next part in my code and it threw NoSuchElementException, and then I realized that this is not the default, where Arraysdo

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;
+4
source share
8 answers

, . , . - , , : 0 null.

, ArrayList . . , , . , .

+3

( ). ArrayList - ( ), . ArrayList .

+12

null 0 Object . : null 0 ( false ) . . Java

ArrayList . , 0, . size() , .

List<Integer> list = new ArrayList<Integer>(10);

()

Collections.fill(list, 0) // int 0 is auto-boxed to `Integers` 0 
+4

:

List<Integer> items = Arrays.asList(new Integer[10]);

10 .

,

Integer[] numbers = new Integer[10];
Arrays.fill(numbers,0);
List<Integer> list = Arrays.asList(numbers);

10 , 0:

+3

ArrayList - , null .

+3

ArrayList , , - (= preallocation) . size 0 (.. ), null ( , ).

, , ArrayList , (, String , char int ).

+2

, Collections.nCopies:

List<Integer> list = new ArrayList<Integer>(Collections.nCopies(10, 0));
+2

, ArrayList , . Collections.nCopies(int n, T o) . BTW CopiesList, CopiesList(int n, E e)

+1

Source: https://habr.com/ru/post/1524396/


All Articles