"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
ArrayList-Exception when elements added beyond size. IndexOutOfBoundException, size Vs capacity
Moderator: admin
-
- Posts: 20
- Joined: Fri May 01, 2020 11:27 am
- Contact:
ArrayList-Exception when elements added beyond size. IndexOutOfBoundException, size Vs capacity
Last edited by saregg on Tue May 05, 2020 4:50 am, edited 2 times in total.
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: ArrayList size vs capacity
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.
Try this:
ArrayList al = new ArrayList();
//set capacity
//add a few elements
//check size
//try to insert an element at different positions.
-
- Posts: 20
- Joined: Fri May 01, 2020 11:27 am
- Contact:
Re: ArrayList size vs capacity
Got it.
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 ??
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);
}
}
Last edited by admin on Tue May 05, 2020 4:38 am, edited 1 time in total.
Reason: Please put code inside [code] [/code]
Reason: Please put code inside [code] [/code]
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: ArrayList size vs capacity
Correct.
Who is online
Users browsing this forum: No registered users and 24 guests