HashMap是基于HashCode的,在所有对象的超类Object中有一个HashCode()方法,但是它和equals方法一样,并不能适用于所有的情况,这样我们就需要重写自己的HashCode()方法。下面就举这样一个例
import java.util.*;
public class Exp2 {
public static void main(String[] args) {
HashMap h2 = new HashMap();
for (int i = 0; i < 10; i++) {
h2.put(new Element(i), new Figureout());
System.out.println("h2:");
System.out.println("Get the result for Element:");
}
Element test = new Element(3);
if (h2.containsKey(test)) {System.out.println((Figureout) h2.get(test));}
else {
System.out.println("Not found");
}
class Element {
int number;
public Element(int n) {
number = n;
}
class Figureout {
Random r = new Random();
boolean possible = r.nextDouble() > 0.5;
public String toString() {
if (possible) {
return "OK!";
} else {
return "Impossible!";
}
}
如果你想有效的使用HashMap,你就必须重写在其的HashCode()。
class Element {
int number;
public Element(int n) {
number = n;
}
public int hashCode() {
return number;
}
public boolean equals(Object o) {
return (o instanceof Element) && (number == ((Element) o).number);
}
}
