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

探究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:

  • 对于"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) { ... }
     *    co

mpact_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的源码以及调用栈来理解具体原因。