Top Ten Errors Java Programmers Make(7)# Java - 爪哇娇娃
b*g
1 楼
7. Comparing two objects ( == instead of .equals)
When we use the == operator, we are actually comparing two object
references, to see if they point to the same object. We cannot compare,
for example, two strings for equality, using the == operator. We must
instead use the .equals method, which is a method inherited by all
classes from java.lang.Object.
Here's the correct way to compare two strings.
String abc = "abc"; String def = "def";
// Bad way
if ( (abc + def) == "abcdef" )
{
......
}
When we use the == operator, we are actually comparing two object
references, to see if they point to the same object. We cannot compare,
for example, two strings for equality, using the == operator. We must
instead use the .equals method, which is a method inherited by all
classes from java.lang.Object.
Here's the correct way to compare two strings.
String abc = "abc"; String def = "def";
// Bad way
if ( (abc + def) == "abcdef" )
{
......
}