-2

How can I initialize the size of an ArrayList? The below code that works for initializing the size of a int array but does not work similarly for ArrayList. It prints 10 for the int array and 0 for the ArrayList. Thank you.

    int[] intArray = new int[10];
    ArrayList<Integer> arrlist = new ArrayList<Integer>(10);

    System.out.println("int array size: " + intArray.length);
    System.out.println("ArrayList size: " + arrlist.size());
user2220115
  • 263
  • 6
  • 10

2 Answers2

2

That is because ArrayLists work differently than standard arrays.

When you pass in 10, you're telling it to allocate space for 10 elements, but since you haven't added anything to the ArrayList yet, size() will return 0.

Try adding an element and then printing the size - that should help you understand how it works. When in doubt, check the docs.

pushkin
  • 9,575
  • 15
  • 51
  • 95
  • 1
    Correct. Typically, the memory for ArrayList type containers is increased by doubling it. Thus, if you initially had space for 10 items and you added 10, the eleventh item will be added to a new (internal) array of 20 items. The reason for this is that the incremental cost of adding items is reduced from O(n^2) if the array had been incremented in fixed size increments to a nice O(n) when doubling the size each time the internal array is full. So setting the size may be more of a matter of memory management. – Dale Oct 29 '15 at 04:52
0

The size that you pass as argument is the initial container size for arraylist. Once you start storing database then only you will get appropriate size for your arraylist. Since the nature of the ArrayList is keep growing/reducing with the data insertion/removal into/from the list.

Vivek Singh
  • 2,047
  • 11
  • 24