为了只查找一次地图并尽可能多地重用我的关键实例,我想知道这样做是否合法:
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;
}
}
我只用 put 进行一次地图查找。但是我可以重用 GroupByOrdKey 实例吗?Javadoc 没有说清楚,值被替换了,但是键实例呢?
是否有任何其他允许此类用例的 Map 实现:
- 只有一个地图查找
- 重用现有的密钥实例
谢谢