java基础—Objcet中的equals方法重写

来源:互联网 发布:如何注册网站域名 编辑:程序博客网 时间:2024/06/06 23:15



package mytest;public class Test1{public static void main(String[] args) {Person p1 = new Person(20);Person p2 = new Person(30);System.out.println(p1.equals(p2));//false}}class Person{private int age;Person(int age){this.age = age;}}

重写equals方法后:


package mytest;public class Test1{public static void main(String[] args) {Person p1 = new Person(20);Person p2 = new Person(20);System.out.println(p1.equals(p2));//true}}class Person{private int age;Person(int age){this.age = age;}public boolean equals(Object obj){if(!(obj instanceof Person)){throw new ClassCastException("类型错误");}Person p = (Person)obj;return this.age==p.age;}}

Objcet 类的toString方法  默认的返回的内容是“对象所属的类名  和 对象的哈希值”

package mytest;public class Test1{public static void main(String[] args) {Person p1 = new Person(20);Person p2 = new Person(20);System.out.println(p1.equals(p2));//trueSystem.out.println(p1.toString());//mytest.Person@37System.out.println(p2.toString());//mytest.Person@37}}class Person{private int age;Person(int age){this.age = age;}public boolean equals(Object obj){if(!(obj instanceof Person)){throw new ClassCastException("类型错误");}Person p = (Person)obj;return this.age==p.age;}public int hashCode(){return 55;}}



0 0