爲了使只有一個查找地圖和重用盡可能我的鑰匙情況下,我想知道這是否是合法的,做到這一點:地圖,使用時再用一個可變的鑰匙放在
public static class GroupByOrdMap {
private final Map<GroupByOrdKey, MutableInt> map = new HashMap<>();
/**
* Increment the value previously associated to key.
* or add a new entry with value 1.
* @param key the key
* @return a reusale GroupByOrdKey or null if there is nothing to reuse
*/
public GroupByOrdKey inc(GroupByOrdKey key) {
MutableInt mu = new MutableInt(1);
MutableInt prev = map.put(key, mu);
if(prev != null) {
mu.add(prev); // increment existing value
// XXX : this key is mutable, but can I safely reuse this instance???
return key;
}
return null;
}
}
// Key, as it can be heavy I would like to reuse it as much as possible
public static class GroupByOrdKey {
private long[] ords;
public GroupByOrdKey(int size) {
ords = new long[size];
}
private void setOrd(int idx, long ord) {
ords[idx] = ord;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(ords);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
GroupByOrdKey other = (GroupByOrdKey) obj;
if (!Arrays.equals(ords, other.ords))
return false;
return true;
}
}
我只用一個地圖查找。 但我可以重用GroupByOrdKey實例嗎? Javadoc沒有說清楚,價值被取代了,但關鍵實例呢?
是否有任何其他Map實現允許這樣的用例:
- 只有一個地圖查找
- 重用現有的密鑰實例
感謝
從這個問題,如果你真的想變異的關鍵它在地圖中使用後,是有些不清楚的代碼? (請參閱下面的dasblinkelights答案)。我建議通過將'ords'聲明爲final來使'GroupByOrdKey'不可變,並且只在構造函數中初始化它。這會打破你的設計嗎? –
重用未使用的密鑰的想法是重用ords數組,所以它不會破壞設計,但我會創建許多ords []數組。 – nomoa