简体   繁体   English

为什么在HashMap中为getEntry定义对象

[英]Why define object for getEntry in HashMap

I am new to generics and I am not sure if the answer to my question is opinion based or has a genuine reason. 我是仿制药的新手,我不确定我的问题的答案是opinion based还是有正当理由。 In the following code what was need to case a key of an entry to an object ? 在下面的代码中,需要设置一个对象条目的键?

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

It appears to be easily replaced by 它似乎很容易被替换

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

More reference: 更多参考:

 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;
    }

This is an extreme optimization measure that is probably not necessary for general purpose programming practice. 这是一种极端优化措施,对于通用编程实践可能不是必需的。 Here is a discussion that could answer your question. 这是一个可以回答你的问题的讨论 Below statement is copied from that post: 以下语句是从该帖子复制的:

It's a coding style made popular by Doug Lea. 这是Doug Lea流行的编码风格。 It's an extreme optimization that probably isn't necessary; 这是一种极端的优化,可能不是必需的; you can expect the JIT to make the same optimizations. 您可以期望JIT进行相同的优化。 (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. (您可以尝试自己检查机器代码!)然而,复制到本地生成最小的字节码,而对于低级代码,编写更接近机器的代码是很好的。

您错过了检查keyk相等性的最后一部分,因此删除赋值(k = e.key)将打破最后一次检查 -

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

If what you want to do with a class requires you jump through hoops, you do. 如果你想要一个课程,你需要跳过篮球,你就可以。 With generics I have had trouble getting it to make sense all the time. 有了泛型,我总是很难让它变得有意义。 sometimes it turns out easier than you would think, other times you try everything you can think of. 有时它比你想象的更容易,有时你会尝试你能想到的一切。 keep at it. 坚持下去。

Looking at the code for Entry, key is "final". 查看Entry的代码,key是“final”。 My take is that this code is creating a non-final variable from the final variable so that constraints of a final variable does not prevent the subsequent code from executing. 我的看法是这段代码是从最终变量创建一个非final变量,这样最终变量的约束不会阻止后续代码的执行。 Other than that, I also would assume as you have said both the "if" conditions should be the same. 除此之外,我还假设你说“if”条件应该是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM