最近在coding的过程遇到一个问题:
public class HashMapDemo { public static void main(String[] args) { testGo(); } public static void testGo() { Map<Long, String> badGodMap = new HashMap<>(); badGodMap.put(23L, "jack"); badGodMap.put(24L, "tom"); Integer oneKey = 23; // oneKey是Integer类型的 System.out.PRintln("integer: " + badGodMap.containsKey(oneKey)); // false Long longKey = 23L; // longKey是Long型的 System.out.println("long: " + badGodMap.containsKey(longKey)); // true }}看了containsKey的源码是要去比较对象的hashCode的以及进行equals判断,让我输出其中的hashCode一探究竟:
public static void testGo() { Map<Long, String> badGodMap = new HashMap<>(); badGodMap.put(23L, "jack"); badGodMap.put(24L, "tom"); Integer oneKey = 23; Long longKey = 23L; System.out.println("integer hashcode: " + getHashCode(oneKey)); // 23 System.out.println("long hashcode: " + getHashCode(longKey)); // 23 } public static int getHashCode(Object key) { return key.hashCode(); }获取的hashcode都是一样的, 那就是在比较equals的时候出问题了,看Integer的equals源码:
public boolean equals(Object obj) { if (obj instanceof Integer) { //focus here return value == ((Integer)obj).intValue(); } return false; }看到这里就明白了,类型不一样,进行equals比较肯定会失败:
Integer oneKey = 23; Long longKey = 23L; System.out.println(oneKey.equals(longKey)); // false新闻热点
疑难解答