在使用集合操作的remove时,会出现以下情况:
按照正常的方法是不能删除的,但是查看remove源码发现底层是用equal来判断到底remove中的参数是否存在于arrayList中的,在new Student("aaa",20)时,一般情况下显然与arraylist中的不是equal的,但我们如果重写用来比较两个Student对象的方法equal方法,令只要名字和年龄相同就认为是同一个对象就可以用remove删除
package collection;
import java.util.ArrayList;
/**
* ArrayList的使用
*/
public class Demo05 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
//1.添加元素
Student s1 = new Student("aaa",20);
Student s2 = new Student("bbb",20);
Student s3 = new Student("ccc",20);
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
System.out.println(arrayList);
//2.删除元素
//按照正常的方法是不能删除的,但是查看remove源码发现底层是用equal来判断到底remove中的参数是否存在于arrayList中的,在new Student("aaa",20)时,
// 一般情况下显然与arraylist中的不是equal的,但我们如果重写用来比较两个Student对象的方法equal方法,令只要名字和年龄相同就认为是同一个对象就可以用remove删除
Student a = new Student("aaa",20);
arrayList.remove(a);
//或者 arrayList.remove(new Student("aaa",20));效果等同
System.out.println(arrayList);
}
}
重写Student类的equals方法
package collection;
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object obj) {
if(this==obj){ return true;}
if(obj==null){ return false;}
if(obj instanceof Student){
Student s = (Student)obj;
if(this.name.equals(s.getName())&&this.age == s.getAge()){
return true;
}
}
return false;
}
}