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

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
saregg
Posts: 20
Joined: Fri May 01, 2020 11:27 am
Contact:

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

Post 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
Last edited by saregg on Tue May 05, 2020 4:50 am, edited 2 times in total.

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: ArrayList size vs capacity

Post 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.

saregg
Posts: 20
Joined: Fri May 01, 2020 11:27 am
Contact:

Re: ArrayList size vs capacity

Post 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 ??
Last edited by admin on Tue May 05, 2020 4:38 am, edited 1 time in total.
Reason: Please put code inside [code] [/code]

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: ArrayList size vs capacity

Post by admin »

Correct.

Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests