为了使只有一个查找地图和重用尽可能我的钥匙情况下,我想知道这是否是合法的,做到这一点:地图,使用时再用一个可变的钥匙放在
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