4 Replies Latest reply: Jan 3, 2011 12:34 AM by Parul Garg RSS

    Removing from Arraylist

    Parul Garg
      I have an ArrayList of selectitems called newRes2 and another Arraylist of String called newentry .
      I want to remove the entry in the newRes2 based on newentry .

      i.e. Suppose newentry has string value "a" and newRes2 also has selectitem with the value "a" . It should remove the entry .

      I tried the same by creating "SelectItem from newentry value " and then the remove method .
      newRes2.remove(new SelectItem(newentry.get(i) ) ));

      But since the objects are different and the output is false.

      Can someone help me with this ? Do i need to over-ride equals method in this case ?

      Thanks.
        • 1. Re: Removing from Arraylist
          800330
          Yes, removing from a [url http://download.oracle.com/javase/6/docs/api/java/util/List.html#remove(java.lang.Object)]List is based on equals() (see the documentation) and should be implemented according to the desired behavour in your class.
          • 2. Re: Removing from Arraylist
            802316
            If you want two SelectItems to be equals you need to override equals() to reflect this.

            However, another approach is to remove all the SelectItems which have a stringValue() contained in the collection newEntry.
            for(iterator<SelectItem> iter = newRes2.iterator(); iter.hasNext();)
              if (newentry.contains(iter.next().stringValue()) iter.remove();
            • 3. Re: Removing from Arraylist
              gimbal2
              if SelectItem is a class you created yourself then giving it a proper equals() method could do it, yes.

              If for some reason you cannot get it to work, I would just iterate through the list and inspect the object inside it. When you find the index you want to remove, use the Iterator.remove() method to pluck it out.
              • 4. Re: Removing from Arraylist
                Parul Garg
                Thanks Peter for the solution.