集合remove()方法相关问题

学习集合的过程中,了解到一个有关于remove()方法的有关特性,特此记录

首先remove方法的格式:

collection.remove(Object o);

这是指对集合collection内的某对应的元素o进行移除操作。

学习过程中,经过老师的提问,当我们将o换成一个匿名对象,是否也可以经过比较进行删除该元素?示例如下(创建一个Student类,类中只有age和name变量):

Collection collection = new ArrayList();
Student s1 = new Student(10,"a");
Student s2 = new Student(12,"b");
Student s3 = new Student(13,"c");

//添加三个元素
collection.add(s1);
collection.add(s2);
collection.add(s3);

//删除前
System.out.println(collection.size());
for (Object o: collection) {
     Student s = (Student) o;
     System.out.println(s.getAge() + s.getName());
}
collection.remove(new Student(10,"a"));
//删除后
System.out.println(collection.size());
for (Object o: collection) {
    Student s = (Student) o;
    System.out.println(s.getAge() + s.getName());
}

当运行这段代码后,结果为:

image-20220208221535151

也就是说,这个没法这样删除掉,那非要这么用可以做到吗

答案是可以的,这个涉及到remove方法中的源码(但是我很菜所以直接写上老师的回答,在此记录一下QWQ):

remove方法内的大致逻辑是,比较形参和集合内元素是否相等,这种相等不仅要元素内容相等,并且地址也要相同,其使用的方法为equals()方法进行的判断。

那么使用equals()判断就很简单了,在Student类中重写equals方法,让他不需要判断地址就可以了

@Override
public boolean equals(Object o) {
    if (this == o) 
        return true;
    if (o == null || getClass() != o.getClass()) 
        return false;
    Student student = (Student) o;
    return age == student.age && Objects.equals(name, student.name);
    }

当重写之后,针对remove方法中使用的equals方法也就重写了,这样就可以不必比较地址,以同样的代码运行,结果为:

image-20220208222033112

10 a的结果少了,说明删除成功。


这个解释不够完美,没有涉及很底层,因为在我现在的认知里,接口的方法是没有方法体的,我不理解没有方法体如何实现方法,所以这里只是先做个笔记,如果有懂的大佬,可以指导我一下吗谢谢QWQ

再者,就是赞赏一下idea真是方便鸭,重写equals方法直接快捷点几个按键就直接帮我生成了!好感+1