Page 1 of 1

ArrayList-Exception when elements added beyond size. IndexOutOfBoundException, size Vs capacity

Posted: Tue May 05, 2020 2:32 am
by saregg
"Remember that insertion of an element depends the
size (and not capacity ) of the ArrayList. For example,
if the size of an ArrayList is 5, you can't insert an
element at index 6 even if the capacity of that ArrayList
is 10. It will throw an IndexOutOfBoundsException." can anyone provide example for this, couldn't get it. Thanks in advance

Re: ArrayList size vs capacity

Posted: Tue May 05, 2020 2:49 am
by admin
What happened when you created a sample program to test it out?
Try this:
ArrayList al = new ArrayList();
//set capacity
//add a few elements
//check size
//try to insert an element at different positions.

Re: ArrayList size vs capacity

Posted: Tue May 05, 2020 4:31 am
by saregg
Got it.

Code: Select all

 class TestClass {
     public static void main(String[] args) {
         ArrayList<String> al = new ArrayList();
         al.ensureCapacity(5);
         al.add("alice");//[alice]
         al.add("dnd");
         al.add("bob");//[alice, bob]
         al.add("charlie");//[alice, bob, charlie]
         al.add(2, "david");//[alice, bob, david, charlie]
         System.out.println(al.size()); // prints the size
         al.add(10,"heel");                           // IndexOutOfBoundException
         //al.remove(0);//[bod, david, charlie]
         for (Object o : al) { //process objects in the li
             //st
             String name = (String) o;
             System.out.println(name + " " + name.length());
         }
//dump contents of the list
         System.out.println("All names: " + al);
     }
 }
 
So the size only increases if elements are appended at the end of the list. But if tired to insert a element beyond the size+1 within capacity or beyond capacity will cause error. correct ??

Re: ArrayList size vs capacity

Posted: Tue May 05, 2020 4:37 am
by admin
Correct.