为什么要在 HashMap 中为 getEntry 定义对象 [英] Why define object for getEntry in HashMap

查看:32
本文介绍了为什么要在 HashMap 中为 getEntry 定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是泛型新手,我不确定我的问题的答案是 opinion based 还是有真正的原因.在下面的代码中,需要对对象条目的键进行大小写?

I am new to generics and I am not sure if the answer to my question is opinion based or has a genuine reason. 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))))

它似乎很容易被替换为

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

推荐答案

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

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:

这是 Doug Lea 流行的一种编码风格.这是一个可能没有必要的极端优化;您可以期望 JIT 进行相同的优化.(您可以尝试自己检查机器代码!)不过,复制到本地会产生最小的字节码,对于低级代码,最好编写更接近机器的代码.

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.

这篇关于为什么要在 HashMap 中为 getEntry 定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆