是否==为您在布尔完全平等? - Java的 [英] Does == check for full equality in Booleans? - 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>intern$c$c>ing,这是特定字符串(有没有类似布尔
)。还要注意的是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
Boolean
s (the object wrapper, note the capitalB
) orboolean
s (the primitive, note the lower caseb
). If you're talking aboutBoolean
s (the object wrapper), as with all objects,==
checks for identity, not equivalence. If you're talking aboutboolean
s (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 twoString
variables refer to the sameString
instance. Of course, oneString
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 reportfalse
for differentString
instances even if they have the same characters in the same order. That's why we useequals
on them, not==
. Strings can get a bit confusing because ofintern
ing, which is specific to strings (there's no equivalent forBoolean
). Also note that Java doesn't have primitive strings like it does primitiveboolean
,int
, etc.这篇关于是否==为您在布尔完全平等? - Java的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!