在Java中,我有一个类:HashMap对象键
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; }解决方案的缺点是可以从该类之外修改关键值。 – Delta 2013-03-18 01:28:52