How can I correctly remove an Object from ArrayList?

前端 未结 3 1873
小蘑菇
小蘑菇 2020-12-21 03:44

I’m trying to remove an object from an ArrayList. Each Item object has 3 attributes; 1. itemNum 2. info 3. cost. I also have 3 classes, 1. Item class defines the single item

相关标签:
3条回答
  • 2020-12-21 04:01

    Use ArrayList.remove()

    Make sure you have overridden equals in your object class.

    0 讨论(0)
  • 2020-12-21 04:06

    Override equals method in your Item class. You can use itemNum to check the equality of objects in your equals method.

    Then use ArrayList remove(Object o) method to delete the object. The remove method uses equals internally to find the object to be removed.

    EDIT:

    You are not overriding the equals method properly, here is the right signature and implementation:

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Item other = (Item) obj;
        if (itemNum != other.itemNum)
            return false;
        return true;
    }
    
    0 讨论(0)
  • 2020-12-21 04:17

    To remove the object from the list you need to find out the object first. You can implement Comparable interface and override compareTo() method to find out the object.

    Public class CatalogItem implements Comparable
    {
     private int itemNum;
     private String info;
     private double cost;
     private int itemNum;
    
    
    public Item()
    {   //start constructor
     itemNum = 0;   //default values
     info = "x";
     cost = 0;
    }   //end constructor
    
    
    public CatalogItem(int newItemNum, String newInfo, double newCost)
    {   //start overload constructor
     this.itemNum = newItemNum;
     this.info = newInfo;
     this.cost = newCost;
    }   //end overload constructor
    
    public int compareTo(catalogItem c){
      if(c.getItemNum == this.getItemNum()){
         return 0;// zero means both are equal
      }
    }
    }
    

    When you get teh itemNum form input, the create a CatalogItem object and set this value and iterate through list to check equality. If you find it then remove from the list, but make sure you are not removing from the same list otherwise you can get Concurrency Exception.

    0 讨论(0)
提交回复
热议问题