Win a copy of Head First Android this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Can the index number be specified in the ArrayList add method

 
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Sheriff
Posts: 22508
122
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic