== 检查布尔值是否完全相等?- 爪哇

2022-01-19 00:00:00 boolean equals-operator java

所以我听说如果我将 2 个字符串与 == 进行比较,那么只有当它们都引用同一个对象/实例时,我才会返回 true.那是字符串.布尔值呢?

So I've heard that if I compare 2 strings with == then I will only get true back if they both refer to the same object/instance. That's strings. What about Booleans?

推荐答案

== 检查布尔值是否完全相等?- 爪哇

Does == check for full equality in Booleans? - Java

这取决于您是在谈论 Booleans(对象包装器,注意大写 B)还是 booleans(原语,注意小写 b).如果您谈论的是 Booleans(对象包装器),与所有对象一样,== 会检查 identity,而不是 等价.如果您在谈论 booleans(原语),它会检查是否等价.

It depends on whether you're talking about Booleans (the object wrapper, note the capital B) or booleans (the primitive, note the lower case b). If you're talking about Booleans (the object wrapper), as with all objects, == checks for identity, not equivalence. If you're talking about booleans (primitives), it checks for equivalence.

所以:

Boolean a, b;
a = new Boolean(false);
b = new Boolean(false);
System.out.println("a == b? " + (a == b)); // "a == b? false", because they're not the same instance

但是

boolean c, d;
c = false;
d = false;
System.out.println("c == d? " + (c == d)); // "c == d? true", because they're primitives with the same value

<小时>

关于字符串:


Regarding strings:

我听说如果我将 2 个字符串与 == 进行比较,那么只有当字符串相同并且它们都引用相同的对象/实例时,我才会返回 true...

I've heard that if I compare 2 strings with == then I will only get true back if the strings are identical and they both refer to the same object/instance...

这不是真正的与":== 将仅检查两个 String 变量是否引用相同的 String 实例.当然,一个 String 实例只能有一组内容,所以如果两个变量都指向同一个实例,那么内容自然是相同的... :-) 关键是 == 将报告 不同 String 实例的 false,即使它们具有相同顺序的相同字符.这就是为什么我们在它们上使用 equals,而不是 ==.由于 interning,特定于字符串(Boolean 没有等价物,尽管当您使用 Boolean.valueOf(boolean),你会得到一个缓存的对象).另请注意,Java 不像原始 booleanint 等那样具有原始字符串.

It's not really an "and": == will only check whether the two String variables refer to the same String instance. Of course, one String instance can only have one set of contents, so if both variables point to the same instance, naturally the contents are the same... :-) The key point is that == will report false for different String instances even if they have the same characters in the same order. That's why we use equals on them, not ==. Strings can get a bit confusing because of interning, which is specific to strings (there's no equivalent for Boolean, although when you use Boolean.valueOf(boolean), you'll get a cached object). Also note that Java doesn't have primitive strings like it does primitive boolean, int, etc.

相关文章