package com.tarena.corejava.day10; /** * 该类展示equals/hashCode两个方法的实际开发中的标准写法 * @author Administrator * */ public class TestEqualsHashCode { private int id; private String name; public TestEqualsHashCode(int id, String name) { super(); this.id = id; this.name = name; } @Override public boolean equals(Object obj) { if(obj == null) return false; if(this.getClass()==obj.getClass()){//利用反射取确切的类型 TestEqualsHashCode tec = (TestEqualsHashCode)obj; return tec.id == this.id;//比较基本数据类型用== //return tec.name.equals(this.name);//比较引用类型用equals } return false; } @Override public int hashCode() { int type = this.getClass().hashCode(); int code = type*31+id; System.out.println("Hash码"+code); return code; //return type*31 +name.hashCode();//返回引用类型的hashCode的方法,引用.hashCode } public static void main(String[] args) { TestEqualsHashCode tec1 = new TestEqualsHashCode(1,"alpha"); TestEqualsHashCode tec2 = new TestEqualsHashCode(2,"jack"); TestEqualsHashCode tec3 = new TestEqualsHashCode(1,"alpha"); System.out.println(tec1.equals(tec2)); System.out.println(tec1.equals(tec3)); if(tec1.hashCode() == tec2.hashCode()){ System.out.println("hashCode相同"); }else{ System.out.println("hashCode不相同"); } } }