How to remove specific object from ArrayList in Java?

前端 未结 13 1650
旧时难觅i
旧时难觅i 2020-12-05 06:54

How can I remove specific object from ArrayList? Suppose I have a class as below:

import java.util.ArrayList;    
public class ArrayTest {
    int i;

    pu         


        
13条回答
  •  佛祖请我去吃肉
    2020-12-05 07:41

    ArrayList removes objects based on the equals(Object obj) method. So you should implement properly this method. Something like:

    public boolean equals(Object obj) {
        if (obj == null) return false;
        if (obj == this) return true;
        if (!(obj instanceof ArrayTest)) return false;
        ArrayTest o = (ArrayTest) obj;
        return o.i == this.i;
    }
    

    Or

    public boolean equals(Object obj) {
        if (obj instanceof ArrayTest) {
            ArrayTest o = (ArrayTest) obj;
            return o.i == this.i;
        }
        return false;
    }
    

提交回复
热议问题