How can I correctly remove an Object from ArrayList?

前端 未结 3 1903
小蘑菇
小蘑菇 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: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;
    }
    

提交回复
热议问题