• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can the index number be specified in the ArrayList add method

 
Varuna Seneviratna
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can the index number be specified in the ArrayList add method
If the first elemnt to be added is four


4 specified as the index number, which should place four in the forth place in the il ArrayList.Is this posible?

The below program uses a feature like that





When I specified four as the index number of zero the first addition to the list the message was
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size:
0
at java.util.ArrayList.add(ArrayList.java:367)
at ArrayListMagnet.main(ArrayListMagnet.java:10)


If the index number can be specified when an element is added, what is the use if the index number can not be a choice of the programmer?


Varuna
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can only specify an index that is less than the number of elements already in the ArrayList, so you can only use 4 if you already have four or more elements in the list.
[ October 02, 2008: Message edited by: Joanne Neal ]
 
Rob Spoor
Sheriff
Pie
Posts: 20514
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Varuna Seneviratna:

You can't use ArrayList<int>, but ArrayList<Integer> is a very close match thanks to auto(un)boxing.

Originally posted by Joanne Neal:
You can only specify an index that is less than the number of elements already in the ArrayList

Or equal to the number of elements
If that's the case it's added to the end.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic