if(foo != bar)
Log(foo + " is not equal to " + bar);
Prints:
FooBar@ca4c33db is not equal to FooBar@ca4c33db
This is happening on Android. FooBar is my own custom class. I double-checked it in the debugger.
if(foo != bar)
Log(foo + " is not equal to " + bar);
Prints:
FooBar@ca4c33db is not equal to FooBar@ca4c33db
This is happening on Android. FooBar is my own custom class. I double-checked it in the debugger.
You should use equals()
if(!foo.equals(bar))
But with String
you can do following since String
class has implemented equals()
method.
String a = "hi";
String b = "hii";
if (a!=b){
System.out.println("yes");
}else {
System.out.println("no");
}
Out put:
yes
If you want to go with your way you must override equals()
method.
Example: With out override equals()
public class Test {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Now take a look at this
Test a = new Test();
Test b = new Test();
a.setAge(1);
a.setName("hi");
b.setAge(1);
b.setName("hi");
if (a!=b){
System.out.println("yes");
}else {
System.out.println("no");
}
Out put:
yes
Now you can see same issue here.
There are a handful of things to note on this question.
Normally == is not accurate since it compares "memory addresses" (or as near as that can be in the JVM) and not the contents of the objects.
You should override .equals() method in order to compare every significant field of the objects. If your objects need this, they need an override too of the .hashCode() method according to Josh Bloch in Effective Java (or your objects would behave poorly when hashed into a Map)
Only if you guaranteed that your objects are immutable and that you don't create new instances for objects with the same value (say Boolean objects generated with Boolean.valueOf(true/false)
) you could use that == ; in any other case, you need a .equals() method (or make them implement Comparable and try foo.compareTo(bar) == 0
)
Because they are different objects.
Try changing a field/member in one object, and see if the field in the other object is changed as well.