1、通过索引删除

remove(index);

2、通过对象删除

public Boolean remove(Object obj){
    // 如果对象为null,遍历集合查找集合中是否有为null的元素 
    if(obj == null) {
        for(int index; index < size; index++){
            if(elementData[index] == null) {
                fastRemove(index);
                return true;
            }
        }
    } else {
        for(int index; index < size; index++) {
            // 通过equals()方法比较是否为同一对象
            if(obj.equals(elementData[index])) {
                fastRemove(index);
                return true;
            }
        }
    }
    return false;
}

注意:

ArrayList的remove(Object obj)方法判断是否为同一个对象的时候用的是equals方法,如果我们要移除list中的自定义类的时候需要重写equals方法,否则调用父类Object 的 equals方法,比较两个元素是否为同一对象的时候底层是通过==比较的(比较引用类型的引用地址),导致删除不了目标对象的方法。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐