Java中的Map是以Key-Value的形式进行存储的。Map对于基础类型(见下面注释) 作为Key 保证了Key的唯一性,但是如果插入自定义类型作为Key,我们就需要自己维护Map中Key的唯一性:
基础类型/ 即已经实现Comparable的常用类:
1.所有数值的包装类
2.Character (char 的包装类)
3.Boolean (bool 的包装类)
4.String
5.BigDecimal,BigInteger类
6.Date,Time
此时我们需要重写 overrides java.lang.Object.hashCode 和 overrides java.lang.Object.equals 两个方法。
java.lang.Object.equals 方法:
public boolean equals(Object obj) {
return (this == obj);
}
java.lang.Object.hashCode 方法:
public native int hashCode();//native 关键字表示该方法交由C来实现
示例:不重写equals 和 hashCode会导致可以插入重复对象:
import java.util.HashMap;
import java.util.Map;
class A {
public int a;
A(int a) {
this.a = a;
}
// public boolean equals(Object dest) {
// if (this.a == ((A) dest).a) {
// return true;
// } else {
// return false;
// }
// }
//
// public int hashCode() {
// return this.a;
// }
}
public class NullHashMap {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map hMap = new HashMap();
hMap.put(new A(5), null);
hMap.put(new A(5), null);
// hMap.put("a", null);
System.out.println(hMap);
}
}
示例:只重写equals , 不重写hashCode会导致可以插入重复对象:
import java.util.HashMap;
import java.util.Map;
class A {
public int a;
A(int a) {
this.a = a;
}
public boolean equals(Object dest) {
if (this.a == ((A) dest).a) {
return true;
} else {
return false;
}
}
//
// public int hashCode() {
// return this.a;
// }
}
public class NullHashMap {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map hMap = new HashMap();
hMap.put(new A(5), null);
hMap.put(new A(5), null);
// hMap.put("a", null);
System.out.println(hMap);
}
}
示例:不重写equals , 只重写hashCode会导致可以插入重复对象:
import java.util.HashMap;
import java.util.Map;
class A {
public int a;
A(int a) {
this.a = a;
}
// public boolean equals(Object dest) {
// if (this.a == ((A) dest).a) {
// return true;
// } else {
// return false;
// }
// }
public int hashCode() {
return this.a;
}
}
public class NullHashMap {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map hMap = new HashMap();
hMap.put(new A(5), null);
hMap.put(new A(5), null);
// hMap.put("a", null);
System.out.println(hMap);
}
}
示例:重写 equals 和 hashCode,可以避免插入重复对象。
import java.util.HashMap;
import java.util.Map;
class A {
public int a;
A(int a) {
this.a = a;
}
public boolean equals(Object dest) {
if (this.a == ((A) dest).a) {
return true;
} else {
return false;
}
}
public int hashCode() {
return this.a;
}
}
public class NullHashMap {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map hMap = new HashMap();
hMap.put(new A(5), null);
hMap.put(new A(5), null);
// hMap.put("a", null);
System.out.println(hMap);
}
}
重写hashCode 方法 较为复杂,请参考其他资料