java - 为什么要在 HashMap 中为 getEntry 定义对象

标签 java generics hashmap

我是泛型的新手,我不确定我的问题的答案是基于意见还是有真正的理由。在下面的代码中,需要什么来区分对象条目的键?

Object k;
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))

它似乎很容易被替换为

if (e.hash == hash && (e.key == key || (key != null && key.equals(e.key))))

更多引用:

 final Entry<K,V> getEntry(Object key) {
        int hash = (key == null) ? 0 : hash(key);
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

最佳答案

这是一种极端的优化措施,对于通用编程实践来说可能不是必需的。这是一个 discussion那可以回答你的问题。以下声明是从该帖子中复制的:

It's a coding style made popular by Doug Lea. It's an extreme optimization that probably isn't necessary; you can expect the JIT to make the same optimizations. (you can try to check the machine code yourself!) Nevertheless, copying to locals produces the smallest bytecode, and for low-level code it's nice to write code that's a little closer to the machine.

关于java - 为什么要在 HashMap 中为 getEntry 定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19395003/

相关文章:

java - 我可以通过在子类中包含父类来以递归方式反序列化 json 吗?

c# - 使用动态类型而不是不可能的通用属性

java - 为什么指定Map的初始容量会导致后续序列化给出不同的结果?

java - 使用 java 8 对 Map<String, List<Object>> 进行排序

java - 按每个单词查找文本文件的行号

java - 如何安装antlr4?

c# - 将 IList<T> 转换为 BindingList<T>

c# - 通用线性插值器 : how to cope with DateTime?

java - Java 中发生冲突时迭代 hashmap

java - 未分类的MongoDbException : Command failed with error 10107 (NotMaster): 'not master' on server