【发布时间】:2013-03-18 01:00:54
【问题描述】:
在 Java 中,我有一个类:
public static class Key {
int[] vector = null;
private int hashcode = 0;
Key (int[] key) {
vector = new int[key.length];
// here is the problem
System.arraycopy(key, 0, vector, 0, key.length);
}
public int hashCode() { ... }
public boolean equals(Object o) { ... }
}
作为HashMap<Key, int[]> map 中的一个键。在我做的代码中:
// value int[] array is filled before
map.put(new Key(new int[] {5, 7}), value);
但这会创建一个参数数组 {5, 7} 两次 - 第一次是在调用 Key 构造函数时,然后在该构造函数内部。
我不能使用HashMap<int[], int[]> map,因为不清楚hashCode 将用于int[]。所以我在Key 类中封装了int[] 键。
如何只创建一次参数数组(可以是不同大小的)?
我不喜欢这个解决方案:
map.put(new Key(5, 7), value);
// and rewrite the constructor
Key (int a1, int a2) {
vector = new int[2];
vector[0] = a1;
vector[1] = a2;
}
因为通常参数数组可以有各种大小。
【问题讨论】:
-
为什么不能将数组分配给向量成员?像这样 Key(int[] keys) { this.vector = keys;解决方案的缺点是可以从这个类之外修改键值。