实例:新建一个Person类,像List中添加Person,进行contains和remove方法的测试。
Person类: name和age两个属性,但是没有重写equals方法
public class Person {
private String name;
private Integer age;
public Person(){
}
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "[name="+this.name+",age="+this.age+"]";
}
}
测试类:
public class Test001 {
public static void main(String[] args) throws Exception {
List<Person> list = new ArrayList<Person>();
list.add(new Person("zhangsan",25));
list.add(new Person("lisi",25));
list.add(new Person("lisi",25));
boolean b1 = list.contains(new Person("lisi",25));
System.out.println(b1);
System.out.println(list.toString());
boolean b2 = list.remove(new Person("lisi",25));
System.out.println(b2);
System.out.println(list.toString());
}
}
结果:list中不存在new Person("lisi",25),也没有将new Person("lisi",25)从list中删除。
查看下ArrayList contains和equals的源码:
contains:
remove源码:
查看源码后结论:ArrayList的contains和remove方法依赖对象的equals。
在Person类中没有重写equals方法时候,对两个Person进行equals比较。
Person p1 = new Person("lisi",25);
Person p2 = new Person("lisi",25);
System.out.println(p1.equals(p2));//false
得到的结果是false。
因为没有重写equals方法,调用的是Object的equals方法,当且仅当对象和自己比较的时候才返回true。
Person重写equals方法:
public class Person {
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "[name=" + this.name + ",age=" + this.age + "]";
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof Person)) {
return false;
}
Person other = (Person) obj;
return this.name.equals(other.name) && this.age == (other.age);
}
}
测试类:
public class Test001 {
public static void main(String[] args) throws Exception {
Person p1 = new Person("lisi",25);
Person p2 = new Person("lisi",25);
System.out.println("两个name和age一样的Person是否一致:"+p1.equals(p2));
List<Person> list = new ArrayList<Person>();
list.add(new Person("zhangsan",25));
list.add(new Person("lisi",25));
list.add(new Person("lisi",25));
boolean b1 = list.contains(new Person("lisi",25));
System.out.println("测试contains"+b1);
System.out.println(list.toString());
boolean b2 = list.remove(new Person("lisi",25));
System.out.println("测试remove"+b2);
System.out.println(list.toString());
}
}
结果:
所以在新建类的时候,一定要注意重写equals方法。