Results 1 to 3 of 3
  1. #1
    randoms:) is offline Member
    Join Date
    Apr 2011
    Location
    Glasgow
    Posts
    5
    Rep Power
    0

    Smile Adding an item to arrayList at a specific index

    Hi, Im trying to add an element to a specific index in an ArrayList
    I know for an arrayList if you want to add an element to a specific place you do write arraylist.add(1, 5) to add 5 to position 1, but do you know how to put a variable name in instead of a number.

    I tried arrayList.add(count, 5) where count equals an integer but I keep getting an out of bounds exception

    Count will constantly change and i need to add the elements to the index which equals it.

    Any help would be greatly appreciated

    Thank you very much :)

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    5

    Default

    ArrayList.add
    ->
    Throws:
    IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

    If the size of your ArrayList is lower than count, you will get this exception!

    Example: You can not invoke add(3,1337) if your ArrayList has only one element in it! (Index: 3, Size: 1)

    Btw: size = the number of elements in this list (not the initialCapacity!!!!)

  3. #3
    randoms:) is offline Member
    Join Date
    Apr 2011
    Location
    Glasgow
    Posts
    5
    Rep Power
    0

    Default

    Thank you soo much!!
    I just initalised all the elements in my arrayList to 0 and then did it and it worked!!!

    :D

Similar Threads

  1. Help required with complex method: adding item
    By nignogs in forum New To Java
    Replies: 14
    Last Post: 05-11-2011, 01:06 PM
  2. get specific arrayList from collection
    By computerbum in forum New To Java
    Replies: 1
    Last Post: 03-23-2011, 04:11 AM
  3. NullPointer adding an item to a LinkedList
    By sehudson in forum New To Java
    Replies: 7
    Last Post: 03-10-2011, 03:39 AM
  4. Inserting a SWT tree item at an index
    By Java Tip in forum SWT Tips
    Replies: 0
    Last Post: 07-07-2008, 04:55 PM
  5. grabbing an item from an arraylist.
    By newtojava7 in forum New To Java
    Replies: 1
    Last Post: 03-17-2008, 08:25 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •