Complex key search for HashMap
关键是:重写equals和hashCode。两者缺一不可。
hashCode可以简单的返回一个整数。
import java.util.HashMap;
/*
* Created on Jun 5, 2005
*
* TODO To change the template for this generated file go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class HashMapFinder {
public static void main(String[] args) {
HashMap h = new HashMap();
h.put(new MyOb("1", "2"), "a");
h.put(new MyOb("2","3"),"b");
// test if the key exists.
System.out.println(h.containsKey(new MyOb("2", "3")));
System.out.println(h.get(new MyOb("2","3")));
System.out.println(h.get(new MyOb("1","2")));
}
}
class MyOb {
private int number;
MyOb(String vv1, String vv2) {
this.v1 = vv1;
this.v2 = vv2;
number =1;
}
/**
* @return Returns the v1.
*/
public String getV1() {
return v1;
}
/**
* @param v1
* The v1 to set.
*/
public void setV1(String v1) {
this.v1 = v1;
}
/**
* @return Returns the v2.
*/
public String getV2() {
return v2;
}
/**
* @param v2
* The v2 to set.
*/
public void setV2(String v2) {
this.v2 = v2;
}
private String v1;
private String v2;
public int hashCode() {
return number;
}
public boolean equals(Object obj) {
if (obj == null)
return false;
else if (obj instanceof MyOb) {
MyOb o = (MyOb) obj;
return this.v1.equals(o.getV1()) && this.v2.equals(o.getV2());
} else
return false;
}
}
相关帖子: