When, as a rule, do you use == equality for a referenced typed variable in Java / C #?

As a kind of follow-up answer to a question entitled “Difference between equals and ==”: in what situations do you find yourself experiencing for reference equality in Java / C #?

+7
java c #
source share
8 answers

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 / ).

+6
source share

For Java, most often you need to see if the link is null:

  if (someReference == null) { //do something } 

It is also quite common with enumerations, but the most common place for using it, which I saw, is in the correctly implemented equals method. The first check checks for reference equality and only makes a more expensive calculation if it returns false.

+5
source share

Since it is so quick and easy, == is the usual part of the Equals() function. If two objects == , then they are Equals , and you do not need further processing. For primitives in Java == is your only option (I don't think it's true C #, but I'm not sure). I use == to check for zero (although more often it is != ). Other than that ... Stick to Equals() . This is a rare and probably symptom of a problem that needs == over Equals .

+2
source share

You can use it for quick equality checks.

For example, if you are comparing with some very large objects that may take some time to iterate, you can save time by seeing if they belong to the same object in the first place

 Compare(LargeObj a, LargeObj b) { if (a == b) return true; // do other comparisons here } 
+1
source share

In C #, the == operator can be overloaded, which means you can compare reference types for logical equality.

Every time a class developer thought it would be logical to compare equality, you can do this using your methods.

At the same time, be careful when checking if (a == b) in C #. This MAY be a reference equal, or MAY be a logical comparison.

To separate the two cases, it would be nice to use the following two methods to be clear:

 object.ReferenceEquals(a, b) a.Equals(b) 

The first is a reference comparison, the second is a logical comparison.

here typical == overload, for reference only:

 public static bool operator ==(RRWinRecord lhs, RRWinRecord rhs) { if (object.ReferenceEquals(lhs, rhs)) { return true; } else if ((object)lhs == null || (object)rhs == null) { return false; } else { return lhs.Wins == rhs.Wins && lhs.Losses == rhs.Losses && lhs.Draws == rhs.Draws && lhs.OverallScore == rhs.OverallScore; } } 
+1
source share

Try to avoid == with objects that are usually defined with a final static, and then passed as members of classes that are serialized.

For example (before we enumerated), I had a certain class that imitated the idea of ​​enumeration. Since the constructor was private, and all allowed instances were defined as final statics, I mistakenly assumed that == is always safe to use on these objects.

For example (entering code without compilation, so excuse me if there are some problems with the code)

 public class CarType implements Serializable { public final static CarType DODGE = new CarType("Dodge"); public final static CarType JEEP = new CarType("JEEP"); private final String mBrand; private CarType( String pBrand ) { mBrand = pBrand; } public boolean equals( Object pOther ) { ... } } 

CarType instances were serialized when used in other objects ... but after materializing (on another JVM instance), the == operation failed.

+1
source share

Basically, you can use == when you "know" that "==" is equivalent to ".equals" (in Java).

This way you can increase productivity.

A simple example where you will see this in the .equals method.

 public boolean equals(Object o) { // early short circuit test if (this == o) { return true; } // rest of equals method... } 

But in some algorithms you have a good knowledge of the objects you work with, so you can rely on == for tests. For example, in containers that work with charts, etc.

0
source share

My personal preferences (C #) should always leave == to indicate reference equality (referring to the same object). If I need logical equivalence, I will use Equals <T>. If I follow this rule evenly, there will never be any confusion.

0
source share

All Articles