1
  1. What is the default size for an arraylist in java 8? As far as I remember and searched on google, everywhere I am finding that it is 10 by default but when I am taking output of the below code, it is printing 0. Is there any changes happened in java 8 related to this?

    ArrayList<String> arrList = new ArrayList<String>();
    System.out.println("size:"+arrList.size());
    
  2. My second query is: when I add some element to the list, then will the size increase by 1.5 times of previous size or it will increase by only 1?

PS: Is there any way to know the current capacity of the arraylist object?

ankitmittal
  • 41
  • 1
  • 2
  • 7
  • 4
    The **size** of an empty list is 0. – Oliver Charlesworth Jun 08 '17 at 18:25
  • 4
    What you mean is 'capacity' not size. – Sundararaj Govindasamy Jun 08 '17 at 18:26
  • Possible duplicate of https://stackoverflow.com/questions/27946920/distinction-between-the-capacity-of-an-array-list-and-the-size-of-an-array, also related are https://stackoverflow.com/questions/8896758/initial-size-for-the-arraylist and https://stackoverflow.com/questions/4172480/whats-meant-by-parameter-int-initial-capacity-in-an-arraylist – Radiodef Jun 08 '17 at 18:29

2 Answers2

2

The initial List has the capacity zero (unless you specify otherwise):

 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

When it has to grow, this is used:

int newCapacity = oldCapacity + (oldCapacity >> 1)

oldCapacity >> 1 is division by two, so it grows by 1.5

The one thing to notice that once you remove elements, the capacity does not change. If you need it to shrink use trimToSize.

The 10 is right actually, but only when you put an element into the ArrayList:

    ArrayList<String> ar = new ArrayList<>();

    Field f = ar.getClass().getDeclaredField("elementData");
    f.setAccessible(true);
    int l = ((Object[]) f.get(ar)).length;
    System.out.println(l); // 0

    ar.add("1");

    int x = ((Object[]) f.get(ar)).length;
    System.out.println(x); // 10
Eugene
  • 102,901
  • 10
  • 149
  • 252
1

I think you are confusing size with capacity. Size is the number of elements you have placed into the arrayList while capacity is the max number of elements the arrayList can take. Once you've reached max, the capacity is doubled(if i remember correctly).

So when you add an element into your arrayList, size will always increase by one. If size is equal to capacity, then capacity will increase.

Bill F
  • 695
  • 11
  • 22