Page 1 of 2 12 LastLast
Results 1 to 20 of 38
  1. #1
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default ArrayList remove an element from the list

    Java Code:
    This is the error code I get when I insert a number into the parameter
    
    java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    	at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    	at java.util.ArrayList.remove(ArrayList.java:387)
    	at Auction.removeLot(Auction.java:155)
    
    
    This is the method where I try to remove an element.
    Has any one an idea of where the problem is?
    
    
    /*
     * Remove the lot with the given lot number
     * @param number The number of the lot to be removed.
     * @return The lot with the given number, or null if
     * there is no such lot.
     */
       public Lot removeLot(int number)
       {
           if(number < 0)
           {
               System.out.println("This number does not exist " + number);
            }
           else{
            Iterator it = lots.iterator();
              while(it.hasNext())
               {                        
                  Lot lot = (Lot) it.next(); //number, description, gethighestbid
                     if(number == lot.getNumber())
                       {
                          lots.remove(number);
                       }
             return lot;
      
               }
              
           }
          return null;
        }

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default

    Looks to me there is no guarantee that the lot number corresponds to the index of said object within the array. Call remove on the object rather than its lot number, or use a Map keyed with the lot number and indexed with the object, which would let you quickly get the Object and remove it from the List

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

    Default

    The iterator can freeze updating of the container it is iterating over.
    Another technique is to use a regular for loop and go thru the list in reverse order. Then when you remove an item it is past where the next item will come from and not cause a problem

  4. #4
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Hello,

    The first element in the arraykist is given number 1 an so on. And I insert a number into the parameter to remove the element with the same number.
    I am not shore what you mean "remove the object rather than its number"?

  5. #5
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Hello,

    The first element in the arraykist is given number 1 an so on. And I insert a number into the parameter to remove the element with the same number.
    I am not shore what you mean "remove the object rather than its number"?

  6. #6
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default

    Indexes for arrays start at 0, for it the first element 'number' is one, you cannot remove from a list an element that does not exist. To remove the object, just pass the object to remove to the remove method. Further, take note of Norm's advice. Modifying a List while iterating can result in a ConcurrentModificationException

  7. #7
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Hello,

    I have tryed for (int i = 0; i > lots-1; i > 0; i--) after an example on internet, but I can't get it to work.
    Any idea of what I am doing wrong?

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

    Default

    but I can't get it to work.
    Any idea of what I am doing wrong?
    No. Not without seeing your code.
    Java Code:
     for (int i = 0; i > lots-1; i > 0; i--)
    What error messages do you get with this?

    Do you know the syntax of the for statement?
    It looks like you need to go to your textbook and review how to write a for statement
    Last edited by Norm; 07-09-2011 at 05:57 PM.

  9. #9
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Hello,
    with this code I am able to loop through the list, but not to remove the number(element) from the list
    Java Code:
     public Lot removeLot(int number)
       {
           if(number <=0)
             {
             System.out.println("This number does not exist " + number);
             }
           else{
               for(number = 0; number < lots.size(); number++)
               
                  if(number == lots.size())
                {
                   lots.remove(number);
                    //System.out.println(lots.get(number));
                }
             // return lot;
           }
           
          return null;
        }

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

    Default

    able to loop through the list, but not to remove the number
    Please explain what happens and why you are not able to remove the element from the list.

    Java Code:
     if(number == lots.size())
    What is the purpose of this statement?
    Is it ever true? Did your println ever print anything?

  11. #11
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    Quote Originally Posted by ralf View Post
    The first element in the arraykist is given number 1 an so on. And I insert a number into the parameter to remove the element with the same number.
    You clearly didn't read the ArrayList API docs properly before using the remove(..) method. If you do, you'll see that when an object is removed, all subsequent objects are shifted down one position to fill the gap. This will mean the indexes in your objects no longer match the ArrayList indexes. So if you try to remove the last object by its index, you'll be trying to use an index past the end of the list.

    When using an unfamiliar class or method always read the API docs carefully.

  12. #12
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Hello,

    Please explain what happens and why you are not able to remove the element from the list.
    I have tryed many different ways to solve this, I realize that the former code I sent was bad code.
    I have written a new code which seems more correct, but it won't work.

    if(number == lots.size())
    It did not print anything. I am trying to match the number from the input with the number from the list. It is wrong way to do it, but I can't figure out what else I should do
    Java Code:
    public Lot removeLot(int number)
       {
           if(number <=0)
             {
             System.out.println("This number does not exist " + number);
             }
           else{
               
               for(int num = number; num < lots.size(); num++)
               
                  if(num == lots.size())
                {
                   lots.remove(number);
                    //System.out.println(lots.get(number));
                }
             // return lot;
           }
           
          return lot; //This one won't compile. It can't find lot
        }

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

    Default

    I am trying to match the number from the input with the number from the list
    Where is the "number from the list"?
    Is it the contents of one of the objects in the list?
    Or is the the index of the object in the list? Remember the indexes of items in the list start at 0


    Java Code:
     if(num == lots.size())
    What is the purpose of this statement?
    It did not print anything
    That means that the statement is never true. If it is not true then the remove is not executed.

  14. #14
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Yes, I now that the first index in an array/list start at zero, but every element in the arraylist in the class has been given a number. So the element at index 0 has been given the number 1. I thought that I could remove the element which has been given number 1 with looping through the list to find number 1 and the remove it.

    public Lot removeLot(int number)// Here I can insert a number
    every element has been given a number when they was added to the list

    I can insert number 5 which maybe is on index 4. If number 5 is found in the list then remove it, it does not matter on which index it is.

    Do I think wrong? is it impossible to search after a given number like that I am trying to do?
    Last edited by ralf; 07-09-2011 at 07:32 PM.

  15. #15
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    I just told you why your method doesn't work, and doWhile has already told you how to remove the correct object. Find the object in the ArrayList that contains the number you're looking for, and pass that object to the ArrayList.remove(..) method.

    Again, if you'd read the ArrayList API docs carefully, this would be clear. It's not rocket surgery...
    Last edited by dlorde; 07-09-2011 at 07:26 PM.

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

    Default

    is it impossible to search after a given number like that I am trying to do?
    Your code does NOT look at the contents of any the elements in lots. It is not searching for anything.

  17. #17
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    Quote Originally Posted by Norm View Post
    Your code does NOT look at the contents of any the elements in lots. It is not searching for anything.
    He had code to find the object containing the right number in his OP, but for some reason he's stripped it all out. In fact, he only needed to change one word in the original to make it work (give or take a misplaced curly brace)...

  18. #18
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Hello again
    I am sorry that I bother you
    With this code I am able to remove elements from the list
    Java Code:
      public Lot removeLot(int number)
      {
       if(number <=0)
           {
               System.out.println("This number does not exist " + number);
            }
           else{
            Iterator it = lots.iterator();
              while(it.hasNext())
               {                        
                  Lot lot = (Lot) it.next(); //number, description, gethighestbid
                     if(number == lot.getNumber())
                       {
                          lots.remove(number);
                       }
             return lot;
      
               }
              
           }
          return null;
        }
    When I insert number 1 to remove element 1, it removes the element from index 1 and not the element with number 1
    How should the code be changes so I can remove the correct element?

    This is the output: I have added three elements to the list. I insert number 1 and number 2 on index 1 is removed and not the element 1 on index 0
    1: AAAA (No bid) // index 0
    2: BBBBB (No bid) // index 1
    3: CCCCC (No bid)// index 2


    1: AAAA (No bid) //index 0
    3: CCCCC (No bid) // index 1

  19. #19
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Hello Thank for your Help! Norm, dlorde and dowhile

    This code work now. It remove the correct element
    Java Code:
      public Lot removeLot(int number)
      {
       if(number <=0)
           {
               System.out.println("This number does not exist " + number);
            }
           else{
            Iterator it = lots.iterator();
              while(it.hasNext())
               {                        
                  Lot lot = (Lot) it.next(); //number, description, gethighestbid
                     if(number == lot.getNumber())
                       {
                          lots.remove(lot);
                       }
             return lot;
      
               }
              
           }
          return null;
        }

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

    Default

    Be sure to test your code with different input.
    I ran a test with similar code:
    Java Code:
          ArrayList<String> lots = new ArrayList<String>();
          lots.add("First");
          lots.add("Second");
          lots.add("Third");
          System.out.println("before: " + lots);
    
          Iterator it = lots.iterator();
          while(it.hasNext())       {                        
            String lot = (String) it.next(); //number, description, gethighestbid
            if(lot.equals("First"))         {
              lots.remove(lot);
              System.out.println("lot=" + lot);
            }
          }
          System.out.println("after: " + lots);
    And get this error:
    before: [First, Second, Third]
    lot=First
    Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification( AbstractList.java:372)
    at java.util.AbstractList$Itr.next(AbstractList.java: 343)
    at TestCode4.main(TestCode4.java:450)

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 12
    Last Post: 07-07-2011, 08:49 PM
  2. ArrayList and remove()
    By Pragz in forum New To Java
    Replies: 1
    Last Post: 04-21-2011, 01:42 AM
  3. remove element contents
    By oliveira in forum XML
    Replies: 5
    Last Post: 12-07-2010, 08:44 AM
  4. Replies: 1
    Last Post: 05-20-2010, 10:17 PM
  5. [SOLVED] ArrayList element to int
    By grahamb314 in forum New To Java
    Replies: 9
    Last Post: 11-22-2008, 05:09 PM

Posting Permissions

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