ArrayList中remove方法为什么无法删除元素呢?
下文笔者展示Arraylist.remove方法---删除数据并未被删除的异常处理方法分享,如下所示
ArrayList中add和remove方法具有什么功能呢?
Java之ArrayList中removeAll()方法具有什么功能呢?
ArrayList.remove方法的功能
用于删除ArrayList中的元素
ArrayList.remove的源码
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
从以上源码,我们可以得知:
元素删除时,所使用的对比方法为equals方法
equals方法对比的是对象的地址,当数组中都是new对象时,此时equals都不同
所以此时remove就无法删除元素
例
public static void main(String[] args) {
ArrayList<Student> array = new ArrayList<>();
Student str = new Student("王二", 88);
Student str1 = new Student("java爱",99);
array.add(str);
array.add(str1);
System.out.println(array.size());
array.remove(new Student("王二",88));
for (Object object : array) {
System.out.println(object.toString());
}
}
-----运行以上代码,将输出以下信息-----
Student [name=王二, age=88]
Student [name=java爱, age=99]
从以上的代码,我们可以看出数组中的元素都没有删除,那么如何删除数组中的对象 我们可以通过改写equals方法,使其达到指定的效果例
@Override
public boolean equals(Object obj) {
if(obj==null) {
return false;
}
if(obj instanceof Student) {
Student s = (Student) obj;
if(this.name.equals(s.name)&&this.age==s.age) {
return true;
}
}
return false;
}
//通过在Student类中改写equals方法
//即可达到ArrayList.remove方法生效
相关阅读:
ArrayList中add和remove方法具有什么功能呢?
Java之ArrayList中removeAll()方法具有什么功能呢?
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


