The relational operators == and != also work with all objects,but their meaning often cunfuses the first-time java programmer.Here's an example:
public class Equivalence {
public static void main (Sting[] args){
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1 == n2);
System.out.println(n1!=n2);
}
}
/*output:false true*/
The statement System.out.println(n1 == n2) will print the result of the boolean comparosin within it.Surely the output shoule be "true" and then "false",since both Integer objects are the same. But while the contents of the objects are the same, the references are not the same .The operators == and != compare object regerences ,so the output is actually "false" and then "true".Naturally ,this surprises people at first.
What if you want to compare the actual contents of an object for equivalence? You must use the special method equals() that exists for all objects(not primitives,which work fine with == and !=).Here's how it's used:
public class EqualsMethod{
public static void main(String[] args){
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1.equals(n2));
}
}
/*output: true*/
The result is now what you expect.Ah,but it's not as simple as that;If you create your own class,like this:
class Value{
int i ;
}
public class EqualsMethod2{
public static void main(Sting[] args){
Value v1 = new Value();
Value v2 = new Value();
v1.i = v2.i = 100;
System.out.println(v1.equals(v2));
}
}
/*output: false*/
things are confusing again: The result is false. This is because the default behavior of equals() is to compare references.So unless you override equals() in your new class you won't get the desired behavior.(Your new class does not override equals(),so the result is not the same as your expect!)
Most of the Java library classes implement equals() so that it compares the contents of objects instead of their references.