首页 > Java > java教程 > 正文

Java String类equals方法的工作机制是什么?

碧海醫心
发布: 2025-03-20 10:14:01
原创
588人浏览过

探究java string类equals方法的工作机制

在学习java string类的equals方法时,我们经常会遇到一些困惑,尤其是当深入到源码时,会发现一些不易理解的现象。今天我们将深入探讨jdk18环境下string类的equals方法的内部逻辑,揭示其中的奥秘。

问题描述

在使用断点调试时,观察到了以下现象:

问题1:

return (anobject instanceof string astring)
       && (!compact_strings || this.coder == astring.coder)
       && stringlatin1.equals(value, astring.value);
登录后复制

这个逻辑似乎在调试过程中循环运行。而且,有时即使字符相同,如"a".equals("a")时,value与astring.value的数组长度也会不同。

问题2:

立即学习Java免费学习笔记(深入)”;

  • 对于"a".equals(new string("a"));,调试时发现传递的参数如图所示:
    [参数图像]
  • 对于"a".equals("a");,调试时发现传递的参数如图所示:
    [参数图像]

这两个例子中,参数在传递到equals方法后,似乎并不总是如预期的"a"。

解答

让我们从string类的源码开始,逐步理解这些现象。首先,关于compact_strings的定义和说明:

    /**
     * if string compaction is disabled, the bytes in {@code value} are
     * always encoded in utf16.
     *
     * for methods with several possible implementation paths, when string
     * compaction is disabled, only one code path is taken.
     *
     * the instance field value is generally opaque to optimizing jit
     * compilers. therefore, in performance-sensitive place, an explicit
     * check of the static boolean {@code compact_strings} is done first
     * before checking the {@code coder} field since the static boolean
     * {@code compact_strings} would be constant folded away by an
     * optimizing jit compiler. the idioms for these cases are as follows.
     *
     * for code such as:
     *
     *    if (coder == latin1) { ... }
     *
     * can be written more optimally as
     *
     *    if (coder() == latin1) { ... }
     *
     * or:
     *
     *    if (compact_strings && coder == latin1) { ... }
     *
     * an optimizing jit compiler can fold the above conditional as:
     *
     *    compact_strings == true  => if (coder == latin1) { ... }
     *    compact_strings == false => if (false)           { ... }
     *
     * @implnote
     * the actual value for this field is injected by jvm. the static
     * initialization block is used to set the value here to communicate
     * that this static final field is not statically foldable, and to
     * avoid any possible circular dependency during vm initialization.
     */
    static final boolean compact_strings;

    static {
        compact_strings = true;
    }
登录后复制

从这段说明可以看出,如果compact_strings为false,value将始终使用utf16编码。这个设置和coder字段密切相关。

接下来,我们看看coder的定义:

    /**
     * the identifier of the encoding used to encode the bytes in
     * {@code value}. the supported values in this implementation are
     *
     * latin1
     * utf16
     *
     * @implnote this field is trusted by the vm, and is a subject to
     * constant folding if string instance is constant. overwriting this
     * field after construction will cause problems.
     */
    private final byte coder;
登录后复制

coder有两个可能的值,分别表示latin1和utf16。我们可以找到与coder同名的方法:

    byte coder() {
        return compact_strings ? coder : utf16;
    }
登录后复制

因此,条件(!compact_strings || this.coder == astring.coder)的意义就很明确了:

如果compact_strings == false,就使用utf16编码,继续检查下一个条件。如果条件不成立,就检查coder是否相同,如果不相同,直接返回false。我们可以用手写代码来理解这个逻辑:

boolean flag = false;
if (!compact_strings) {
    flag = true; // 根据 compact_strings 的说明,这种情况下使用 utf16,忽略 coder 值
} else if (this.coder == astring.coder) {
    flag = true; // 说明 coder 一致
}
登录后复制

然后,stringlatin1.equals(value, astring.value)条件中,内部数据value使用latin1编码规则进行比较。value的定义如下:

    /**
     * The value is used for character storage.
     *
     * @implNote This field is trusted by the VM, and is a subject to
     * constant folding if String instance is constant. Overwriting this
     * field after construction will cause problems.
     *
     * Additionally, it is marked with {@link Stable} to trust the contents
     * of the array. No other facility in JDK provides this functionality (yet).
     * {@link Stable} is safe here, because value is never null.
     */
    @Stable
    private final byte[] value;
登录后复制

因此,equals方法的完整逻辑如下:

  1. 首先判断是否是字符串,如果不是,直接返回false。
  2. 检查是否具有相同的coder(compact_strings的值间接影响coder的一致性比较),如果不同,直接返回false。
  3. 在coder相同的情况下,比较内部数据是否一致,决定最终的比较结果。

补充说明:

关于utf16的比较方式,源码中仅使用了stringlatin1.equals,但如果确定编码规则相同,底层按字节比较的方法仍然适用。如果想要更详细了解utf16的比较,可以进一步研究stringlatin1的实现。

对于断点调试时观察到的“循环运行”现象,实际上并没有循环语句。调试过程中,可能会因为编码比较而导致这种现象。如果发现调试时传递的参数是“gbk”,这可能是因为在比较过程中涉及了编码转换。这需要进一步查看stringlatin1的源码以及调用栈来理解具体原因。

以上就是Java String类equals方法的工作机制是什么?的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号