为什么不直接比较e.key而不是将其分配给变量?

 游太虚傲寰宇 发布于 2023-02-12 15:27

在阅读源代码时HashMap,我遇到了以下代码public V put(K key, V value):

for (Entry e = table[i]; e != null; e = e.next) {
    Object k;
    if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
        V oldValue = e.value;
        e.value = value;
        e.recordAccess(this);
        return oldValue;
    }
}

为什么分配e.keyk比较?为什么不直接比较,如:

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

-------------------更新------------------------

根据@seand的回答,我做了更详细的调查:

import com.test.Test;

    public class Main {
        public static void main(String[] args) {
            Test t = new Test();
            int a = t.a;
            int b = a;
        }
    }

class test有一个int提交了一个;

使用javap -c Main获取类文件内容:

  public static void main(java.lang.String[]);
Code:
   0: new           #2                  // class test/Test
   3: dup           
   4: invokespecial #3                  // Method test/Test."":()V
   7: astore_1      
   8: aload_1       
   9: getfield      #4                  // Field test/Test.a:I
  12: istore_2      
  13: iload_2       
  14: istore_3      
  15: return    

int a = t.a 代表

8:[load the t object]
9:[access the field a]
12:[store the value to a]

参考jvm规范获取[getfield]的信息

int b = a 代表:

13:[load the local variable]
14:[store the value to b];

访问局部变量而不是类字段似乎是合理的.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有