equals和hashCode
package hash_map.hash; import java.util.HashMap; public class TestOne { public static void main(String[] args) { //1.哈希值 //数据比较时,如果数据量比较大,equal就慢,引入哈希值 //hashCode() 值: JVM根据对象的内存地址和其他信息生成一个整型数据 // 2.hashCode 和equqal //两个对象先比较哈希值,如果相等,再通过equal比较结果是true才是真的相等 //如果两个对象的hashCode相等,equal得到的结果不一定是true,哈希冲突 //3.重写equal方法的时候一定要重写hashCode方法 //如果不重写hashCode方法,hashCode不同,保存到hashmap中出返回null //4.如果字段值为易变数据最好不要依赖这个字段 // // User t1 = new User("jack",1); User t2 = new User("jack",1); System.out.println(t1.hashCode()); System.out.println(t2.hashCode()); System.out.println(t1.equals(t2)); HashMap<User, Integer> map = new HashMap<User, Integer>(); map.put(t1, 1); System.out.println(map.get(t2)); } } package hash_map.hash; public class User { private String name; private int age; private String guding = "66"; public User(String name, int age) { super(); 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 boolean equals(Object obj) { return this.name.equals(((User)obj).name) && this.age == ((User)obj).age ; } @Override public int hashCode() { return this.guding.hashCode()*7; } }