是否==为您在布尔完全平等? - Java的 [英] Does == check for full equality in Booleans? - Java

查看:91
本文介绍了是否==为您在布尔完全平等? - Java的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我听说,如果我比较两个字符串用==那么我将只得到真正的回来,如果他们都指向同一个对象/实例。这是字符串。关于布尔什么?


解决方案

  

请问==为您在布尔完全平等? - Java的


这取决于你是否在谈论布尔 S(该对象包装,注意是大写 B )或布尔 S(原始,注意小写 b )。如果你在谈论布尔 S(该对象包装),与所有的对象, == 检查身份的,不是的等同的。如果你在谈论布尔 S(原语),它会检查对等。

所以:

 布尔A,B;
一个=新布尔(假);
B =新布尔(假);
的System.out.println(一个== B'+(一个== b))的; //A == B'假,因为它们不是同一个实例

 布尔C,D;
C = FALSE;
D = FALSE;
的System.out.println(C = D?+(C = D)); //C = D?真,因为它们是同一个值原语


关于字符串:


  

我听说,如果我比较两个字符串用==那么我就只有字符串完全相同获得真正回来,他们都指的是同一个对象/实例...


这是不是一个真正的和 == 检查是否两个字符串变量指的是同一字符串实例。当然,有一个字符串实例只能有一组内容,所以如果两个变量指向同一个实例,自然的内容是一样的... ...的:-)关键的一点是 == 将报告不同的即使他们在同一顺序的相同字符的字符串,实例。这就是为什么我们使用它们等于,而不是 == 。字符串可以得到一个有点混乱,因为<一href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern%28%29\"><$c$c>interning,这是特定字符串(有没有类似布尔)。还要注意的是Java没有原始的字符串像它原始的布尔 INT

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

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.

So:

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

But

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:

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...

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). Also note that Java doesn't have primitive strings like it does primitive boolean, int, etc.

这篇关于是否==为您在布尔完全平等? - Java的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆