Results 1 to 2 of 2
  1. #1
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Need help with ArrayList please...

    Hi,

    When I run this code:

    Java Code:
    		ArrayList<Integer> possibleNumbers = new ArrayList<Integer>();
    		
    		for(int i = 0;i<4;i++)
    		{
    			possibleNumbers.add(i);
    		}
    		
    		for(int element:possibleNumbers)
    		{
    			System.out.println(possibleNumbers.get(element));
    		}
    I get the output:
    0
    1
    2
    3

    But I do not want my ArrayList to include 0. I want it to start from 1. So I modified my code:

    Java Code:
    		ArrayList<Integer> possibleNumbers = new ArrayList<Integer>();
    		
    		for(int i = 1;i<4;i++)
    		{
    			possibleNumbers.add(i);
    		}
    		
    		for(int element:possibleNumbers)
    		{
    			System.out.println(possibleNumbers.get(element));
    		}
    and the output is:

    2
    3Exception in thread "main"
    java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
    at java.util.ArrayList.RangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at myPackage.avdas.main(avdas.java:15)

    Can anyone help me with this?

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default Re: Need help with ArrayList please...

    Change your code to put very large numbers into the arraylist:
    Java Code:
     possibleNumbers.add(i*100);
    and see what happens?
    The contents of the arraylist do not correspond to the indexes to the elements.
    Also add this to the beginning of the second loop:
    Java Code:
     System.out.println("el=" + element);// show the value of the index

Similar Threads

  1. Replies: 12
    Last Post: 07-07-2011, 08:49 PM
  2. copying contents of an ArrayList to another ArrayList
    By ankit1801 in forum New To Java
    Replies: 8
    Last Post: 03-27-2011, 06:07 AM
  3. sorting arraylist based on another arraylist
    By busdude in forum New To Java
    Replies: 4
    Last Post: 02-07-2011, 11:48 AM
  4. Replies: 7
    Last Post: 11-22-2010, 01:26 PM
  5. Replies: 2
    Last Post: 04-21-2008, 11:43 AM

Posting Permissions

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