String 是 Java 中的字符序列吗?

Is String sequence of characters in Java?

String s1 = "a";
System.out.println(s1.equals('a'));

输出:

False

任何人都可以解释一下为什么 false 即使字符串 s1 只有一个字符 'a'.

可能是单引号 '' 和双引号 ""

之间的区别

没有。 charString 在 Java.

中是两个不同的东西

一个char正好是一个单个字符。

另一方面,

A String 零个或多个 个字符。您可以有一个长度为 01> 1 的字符串。但是一个字符只能长度为1.

定义字符的方式是在赋值过程中使用单引号。

char first = 'a' // single quotes

对于字符串,您使用 引号。

String first = "a" // double quotes

如果您使用的是像 Eclipse 或 IntelliJ 这样的 IDE,您可以查看 String.equals() 是如何实现的。如果参数不是 String.

,则该方法检查参数是 String 和 return 的实例

单引号用于文字 char,双引号用于文字 String。 此外,如果您将查看 String class 中的 equals 方法,它会被重写如下:

public boolean equals(Object anObject) {
      if (this == anObject) {
          return true;
      }
      if (anObject instanceof String) {
          String anotherString = (String)anObject;
          int n = count;
          if (n == anotherString.count) {
              char v1[] = value;
              char v2[] = anotherString.value;
              int i = offset;
              int j = anotherString.offset;
              while (n-- != 0) {
                  if (v1[i++] != v2[j++])
                      return false;
              }
              return true;
          }
      }
      return false;
  }

char 既不是 String 的实例 class 也不是它们在堆上引用相同的对象。

了解你为什么会得到false,这对你来说是出乎意料的。首先,你需要了解你的代码

s1.equals('a')

s1String'a'Character,因此您正在比较两个不同的对象。

根据documentation

true if the given object represents a String equivalent to this string, false otherwise

现在,回到 String class.

中的 equals 方法实现
// some more code
if (anObject instanceof String) {
  // code here
  // some more code
 }
 return false;

你可以看到,它正在检查你传递的对象是否是 String 的类型??在你的情况下,No,它是 Character。因此,您得到的结果是 false

人们应该始终参考规范而不是实现(除非有理由怀疑实现是错误的,这里不是这种情况)。在这种情况下,equals 的规范,如上面评论中引用的那样,是 Class String, method equals,它表示:

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

由于 'a' 不是字符串,因此结果为假。 'a' 是类型 char 的文字,但它被装箱以键入 Character 因为 equals 需要引用而 'a' 是一个值。