由于字符串是一个对象,因此需要使用该string.equals(string)
方法来确认两个字符串相等。
但是,为什么使用==
来检查两个字符是否相等char1 == char2
,而不是char1.equals(char2)
?
或许,这将有助于了解上的区别==
VS equals
。
@Test
public void testCharacterEquals() {
//primitive type uses == operator for equals comparasion
char a1 = 'A';
char a2 = 'A';
if (a1 == a2) {
System.out.println("primitive type comparasion: it's equal");
}
//From Java doc; The Character class wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char.
//Object type uses equals method for equals comparasion
Character character1 = 'A';
Character character2 = 'A';
if (character1.equals(character2)) {
System.out.println("object type comparasion: it's equal");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句