1 package object; 2 3 public class Test { 4 public static void main(String[] args) { 5 Person person1=new Person(); 6 person1.setName("ZTT"); 7 8 Person person2=new Person(); 9 person2.setName("ZTT"); 10 11 System.out.println(person1.name.equals(person2.name));//结果:true 12 13 } 14 }
我们都知道equals比较的是内容,很明显上面的结果是true.
然而equals方法的参数对象是Object,那Person也是对象,如果直接使得person.equals(person2)结果又如何呢,答案是false,因为在equals方法中用的是==,比较的是地址,让我们重写Person的equals方法
使得结果为true.
重写equals方法:
1 package object; 2 3 public class Person { 4 public String getName() { 5 return name; 6 } 7 public void setName(String name) { 8 this.name = name; 9 } 10 public int getAge() { 11 return age; 12 } 13 public void setAge(int age) { 14 this.age = age; 15 } 16 String name; 17 int age; 18 19 @Override 20 public boolean equals(Object obj) { 21 Person person=(Person)obj; 22 /*if(person.name.equals(name)&&person.age==age){ 23 return true; 24 } 25 return false;*/ 26 return person.name.equals(name)&&person.age==age; 27 28 } 29 30 }
1 package object; 2 3 public class Test { 4 public static void main(String[] args) { 5 Person person1=new Person(); 6 person1.setName("ZTT"); 7 person1.setAge(10); 8 9 Person person2=new Person(); 10 person2.setName("ZTT"); 11 person2.setAge(10); 12 13 System.out.println(person1.equals(person2));//结果:true 14 15 } 16 }