How can I correctly remove an Object from ArrayList?

前端 未结 3 1909
小蘑菇
小蘑菇 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: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.

提交回复
热议问题