gpt4 book ai didi

java - 映射,使用 put 时重用可变键

转载 作者:行者123 更新时间:2023-12-04 04:55:18 27 4
gpt4 key购买 nike

为了仅对 map 进行一次查找并尽可能多地重用我的关键实例,我想知道这样做是否合法:

    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 进行一次 map 查找。
但是我可以重用 GroupByOrdKey 实例吗? Javadoc 没有说清楚,value 被替换了但是 key 实例呢?

是否有任何其他 Map 实现允许此类用例:
  • 只有一张 map 查询
  • 重用现有的 key 实例

  • 谢谢

    最佳答案

    您应该避免在哈希映射中使用可变键。至少,您需要推迟已添加到哈希映射中的键的更改,直到将其从映射中删除。否则,变异的键将在 map 内变得“无法访问”。

    考虑这个事件序列(为了简单起见,假设 int 的哈希码是 int 本身):

  • 创建一个可变整数 key值为 5
  • 添加 key到哈希映射;它将被散列到对应于具有代码 5 的桶中。
  • 设置 key6 .
  • 尝试添加 key再次到 map 。此时, key 将被散列到哈希码为 6 的桶中。 ,并再次添加到 map 中。
  • 创建查询键 queryKey ,一个可变整数,值为 5 .尝试用它搜索哈希映射。

  • 此时, queryKey5将不再“连接”到 5 的旧 key ,即使它们具有相同的哈希码: key 的实例坐在 5的哈希桶旁不会比较为等于 queryKey , 因为 key的当前值为 6 .本质上,旧 key 及其关联的映射条目变得无法访问。

    关于java - 映射,使用 put 时重用可变键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16837223/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com