在Object类中定义了两个非常重要的方法:
public boolean equals(Object obj) public int hashCode()
import java.util.*; class Dog { private String name; public Dog(String name) { this.name = name; } public boolean equals(Object obj) { if(!(obj instanceof Dog)) return false; if(obj == this) return true; // 这里的强制转换一定是安全的 // 因为经过了上面 instanceof 的检查 Dog other = (Dog)obj; return other.name.equals(this.name); } } public class HashTest { public static void main(String[] args) { Map<Dog, Integer> map1 = new HashMap<Dog, Integer>(); map1.put(new Dog("Kitty"), 20); map1.put(new Dog("Paul"), 10); System.out.println(map1.get(new Dog("Kitty"))); // null } }
import java.util.*; class RobustDog { private String name; public RobustDog(String name) { this.name = name; } public boolean equals(Object obj) { if(!(obj instanceof RobustDog)) return false; if(obj == this) return true; RobustDog other = (RobustDog)obj; return other.name.equals(this.name); } @Override public int hashCode() { return this.name.hashCode(); } } public class HashTest { public static void main(String[] args) { Map<RobustDog, Integer> map2 = new HashMap<RobustDog, Integer>(); map2.put(new RobustDog("Sky"), 20); map2.put(new RobustDog("Seam"), 0); System.out.println(map2.get(new RobustDog("Sky"))); // 结果是 20 } }
equals()方法和hashCode()方法在HashMap中的应用,布布扣,bubuko.com
equals()方法和hashCode()方法在HashMap中的应用
原文:http://blog.csdn.net/neosmith/article/details/22052337