有没有人知道我可以下载一个用Java写的复式表实作?
我需要做这样的事情
1 2 3
_______
a| x y z
b| h l m
c| o a ktable.get(a,1)将返回x
当然,它应该使用任何对象作为键、值等
发布于 2010-06-11 07:13:54
根据您的需要,有两种基本方法。
一种是制作Hashtable的Hashtable (或类似的)。
Hashtable<Integer, Hashtable<String, String>> = ...;另一种方法是构建您自己的表示(Integer,String)对的数据类型,因此您可以这样做:
Hashtable<YourFancyDatatype, String>发布于 2010-06-11 07:32:20
你的问题的答案部分在于之前在SO:Java generics Pair 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
}
}发布于 2010-06-11 07:17:32
我假设您有一个字符/对象数组和一个数量,并希望在您的表中彼此交叉。您可以将每个字符映射到一个介于0 ..并简单地创建一个二维数组Object qtyOfCharacters = ObjectA,其中A是刚刚映射的字符/对象的数量,B是列的数量。
要将字符/对象映射到数字,您应该使用HashMap/HashTable。
这个想法是,如果你访问"a,3“处的元素,你应该写入表charmap.get("a")
https://stackoverflow.com/questions/3019177
复制相似问题