Ответ на ваш вопрос частично лежит в предыдущей вопросы по СО: Java generics Pair<String, String> stored in HashMap not retrieving key->value properly
import java.lang.*;
import java.util.*;
public class Pair<TYPEA, TYPEB> implements Comparable< Pair<TYPEA, TYPEB> > {
protected final TYPEA Key_;
protected final TYPEB Value_;
public Pair(TYPEA key, TYPEB value) {
Key_ = key;
Value_ = value;
}
public TYPEA getKey() {
return Key_;
}
public TYPEB getValue() {
return Value_;
}
public String toString() {
System.out.println("in toString()");
StringBuffer buff = new StringBuffer();
buff.append("Key: ");
buff.append(Key_);
buff.append("\tValue: ");
buff.append(Value_);
return(buff.toString());
}
public int compareTo(Pair<TYPEA, TYPEB> p1) {
System.out.println("in compareTo()");
if (null != p1) {
if (p1.equals(this)) {
return 0;
} else if (p1.hashCode() > this.hashCode()) {
return 1;
} else if (p1.hashCode() < this.hashCode()) {
return -1;
}
}
return(-1);
}
public int hashCode() {
int hashCode = Key_.hashCode() + (31 * Value_.hashCode());
System.out.println("in hashCode() [" + Integer.toString(hashCode) + "]");
return(hashCode);
}
@Override
public boolean equals(Object o) {
System.out.println("in equals()");
if (o instanceof Pair) {
Pair<?, ?> p1 = (Pair<?, ?>) o;
if (p1.Key_.equals(this.Key_) && p1.Value_.equals(this.Value_)) {
return(true);
}
}
return(false);
}
public static void main(String [] args) {
HashMap< Pair<String, int>, String> table = new HashMap<Pair<String,int>, String>();
table.put(new Pair<String, int>("a", 1), "x");
table.put(new Pair<String, int>("a", 2), "y");
table.put(new Pair<String, int>("a", 3), "z");
table.put(new Pair<String, int>("b", 1), "h");
table.put(new Pair<String, int>("b", 2), "l");
table.put(new Pair<String, int>("b", 3), "m");
table.put(new Pair<String, int>("c", 1), "o");
table.put(new Pair<String, int>("c", 2), "a");
table.put(new Pair<String, int>("c", 3), "k");
String val = table.get(new Pair<String, int>("a", 1)); //val is x for this input pair
}
}
aw! Пожалуйста, проверьте проект Guava позже осенью для наших классов Table, которые, я считаю, сделают вас очень счастливыми. http://guava-libraries.googlecode.com –