Delphi Clinic | C++Builder Gate | Training & Consultancy | Delphi Notes Weblog | Dr.Bob's Webshop |
|
To be or not to be equal
Usually when we want to compare different values we use the == operator.
But this operator will not always produce the results we may accept.
When we compare values of primitive types, like int, the result of a compare will be predictable. For example:
/* Compare two ints */ int firstInt = 42; int secondInt = 42; System.out.println((firstInt == secondInt)); /* returns true */Trouble starts when we want to compare different objects, and object instances. If we compare two different object references using the == operator, we will only get true if they reference the same object in memory. But if we don't want to compare object references but object values, we must use the equals method. Every object has got this method, because it is defined in
java.lang.Object
.
But to be useful the object must have over written this method.
Let's take a look at an example with Strings:
1: /* Compare two Strings */ 2: String firstString = "JBuilder 2.0 rocks!"; 3: String secondString = "JBuilder 2.0 rocks!"; 4: 5: System.out.println((firstString == secondString)); /* returns true */ 6: 7: /* Compare two Strings */ 8: firstString = new String("JBuilder 2.0 rocks!"); 9: secondString = new String("JBuilder 2.0 rocks!"); 10: 11: System.out.println((firstString == secondString)); /* returns false */ 12: 13: System.out.println((firstString.equals(secondString))); /* returns is true */The results in line 11 and 13 are predictable. Line 11 returns false, because we are comparing two different object instances, and they aren't the same. The variables firstString and secondString point to two different objects in memory. So in order to test if the strings inside the String object are the same, we must use the equals method (line 13).