获取哈希表上一对整数(键值)的值
Get the value of a Pair of Ints(Key Value) on a HashTable
我做了这样一个哈希表:
Hashtable<Integer, Pair> resul = new Hashtable<Integer, Pair>();
int largo, row, col;
当 "Pair" 是我 class 存储 2 个 Int 时,它看起来像这样:
public class Pair<T, U> {
public final T t;
public final U u;
public Pair(T t, U u) {
this.t = t;
this.u = u;
}
}
所以我在我的 HasTable 上添加了元素:
resul.put(largo, new Pair(row, col + 1));
现在我需要我的数字对(整数)以便显示它们,我如何获得这些数字对?
我想要这样的东西:
if (resul.containsKey(0)) {
//Print my "Pair" numbers here
//or better: Print my first number here
//Print my second number here
}
您可以访问 Hashtable 中的对象,只需通过键值调用它
public synchronized V get(Object key);
示例:
public static void main(String[] args) {
Hashtable<Integer, Pair> result = new Hashtable<Integer, Pair>();
result.put(1, new Pair(1, 1 + 1));
if (result.containsKey(1)) {
Pair pair = result.get(1);
System.out.println(pair.t);
System.out.println(pair.u);
}
}
更好的方法是让实例变量在 class 中保持私有,并使用 getters:
class Pair<T, U> {
private final T t;
private final U u;
public Pair(T t, U u) {
this.t = t;
this.u = u;
}
public T getT() {
return t;
}
public U getU() {
return u;
}
}
因此:
public static void main(String[] args) {
Hashtable<Integer, Pair> result = new Hashtable<Integer, Pair>();
result.put(1, new Pair(1, 1 + 1));
if (result.containsKey(1)) {
Pair pair = result.get(1);
System.out.println(pair.getT());
System.out.println(pair.getU());
}
}
我做了这样一个哈希表:
Hashtable<Integer, Pair> resul = new Hashtable<Integer, Pair>();
int largo, row, col;
当 "Pair" 是我 class 存储 2 个 Int 时,它看起来像这样:
public class Pair<T, U> {
public final T t;
public final U u;
public Pair(T t, U u) {
this.t = t;
this.u = u;
}
}
所以我在我的 HasTable 上添加了元素:
resul.put(largo, new Pair(row, col + 1));
现在我需要我的数字对(整数)以便显示它们,我如何获得这些数字对?
我想要这样的东西:
if (resul.containsKey(0)) {
//Print my "Pair" numbers here
//or better: Print my first number here
//Print my second number here
}
您可以访问 Hashtable 中的对象,只需通过键值调用它
public synchronized V get(Object key);
示例:
public static void main(String[] args) {
Hashtable<Integer, Pair> result = new Hashtable<Integer, Pair>();
result.put(1, new Pair(1, 1 + 1));
if (result.containsKey(1)) {
Pair pair = result.get(1);
System.out.println(pair.t);
System.out.println(pair.u);
}
}
更好的方法是让实例变量在 class 中保持私有,并使用 getters:
class Pair<T, U> {
private final T t;
private final U u;
public Pair(T t, U u) {
this.t = t;
this.u = u;
}
public T getT() {
return t;
}
public U getU() {
return u;
}
}
因此:
public static void main(String[] args) {
Hashtable<Integer, Pair> result = new Hashtable<Integer, Pair>();
result.put(1, new Pair(1, 1 + 1));
if (result.containsKey(1)) {
Pair pair = result.get(1);
System.out.println(pair.getT());
System.out.println(pair.getU());
}
}