aspose file tools*
The moose likes Beginning Java and the fly likes Can the index number be specified in the ArrayList add method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can the index number be specified in the ArrayList add method" Watch "Can the index number be specified in the ArrayList add method" New topic
Author

Can the index number be specified in the ArrayList add method

Varuna Seneviratna
Ranch Hand

Joined: Jan 15, 2007
Posts: 167
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


Varuna Seneviratna
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3646
    
  15
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 ]

Joanne
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19718
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can the index number be specified in the ArrayList add method