Consolidation of responses ...
When, as a rule, do you use == equality over a referenced typed variable in Java / C #?
1. To check for null:
if (a == null) ...
2. For efficiency in creating an equivalent implementation:
boolean equals(Object o) { if (o == null) return false; if (this == o) return true; // Some people would prefer "if (!(o instanceof ClassName)) ..." if (getClass() != o.getClass()) return false; // Otherwise, cast o, leverage super.equals() when possible, and // compare each instance variable ...
3. For efficiency, when you compare enumerations or compare class objects designed in such a way that comparing the identity of an object is equivalent to checking the equivalence of an object (for example, class objects):
enum Suit { DIAMONDS, HEARTS, CLUBS, SPADES } class SomeCardGame { ... boolean static isATrumpCard(Card c) { return (c.getSuit() == TRUMP_SUIT); } }
4. When are you really going to verify the identity of the object, and not the equivalence of the object, for example. a test case that wants to make sure that the class does not refuse to reference an instance of the internal data structure.
boolean iChoseNotToUseJUnitForSomeReasonTestCase() { final List<String> externalList = testObject.getCopyOfList(); final List<String> instanceVariableValue = getInstanceVariableValueViaCleverReflectionTrickTo(testObject, "list"); if (instanceVariableValue == externalList) { System.out.println("fail"); } else { System.out.println("pass"); } }
Interestingly, for point 3, in one article it is suggested that using equals is safer than using .equals (), because the compiler will complain if you try to compare with references to objects that are not of the same class ( http: //schneide.wordpress. com / 2008/09/22 / or-equals / ).
Bert f
source share