You have just chosen the perfect example. Both actually do the same as new ArrayList() calls this(10) ;) But internally it will define a storage array with size 10. The ArrayList#size method, on the other hand, simply returns the size variable, which will only be after adding and removing items. This variable is also the main cause of IOOB Exceptions. Therefore, you cannot do this.
If you check the ArrayList code, you will notice that the ArrayList # add method will call ArrayList # rangeCheck . Range checking actually just takes care of the size variable, not the force length of the array containing the data for the List .
Because of this, you still cannot insert data into index 5 , for example. The internal length of the data array at this point will be 10 , but since you have not added anything to your List , the size variable will still be 0 , and you will get the correct IndexOutOfBoundsException when you try to do this.
just try calling list.size() after initializing List with any size, and you will notice that the returned size will be 0 .
source share