Compare two objects with .equals() and == operator

JavaClassObjectMethodsEquals

Java Problem Overview


I constructed a class with one String field. Then I created two objects and I have to compare them using == operator and .equals() too. Here's what I've done:

public class MyClass {
	
	String a;
	
	public MyClass(String ab) {
		a = ab;
	}
	
	public boolean equals(Object object2) {
		if(a == object2) { 
			return true;
		}
		else return false;
	}
	
	public boolean equals2(Object object2) {
		if(a.equals(object2)) {
			return true;
		}
		else return false;
	}
	
	
	
	public static void main(String[] args) {
		
		MyClass object1 = new MyClass("test");
		MyClass object2 = new MyClass("test");
		
		object1.equals(object2);
		System.out.println(object1.equals(object2));
		
		object1.equals2(object2);
		System.out.println(object1.equals2(object2));
	}
	

}

After compile it shows two times false as a result. Why is it false if the two objects have the same fields - "test"?

Java Solutions


Solution 1 - Java

== compares object references, it checks to see if the two operands point to the same object (not equivalent objects, the same object).

If you want to compare strings (to see if they contain the same characters), you need to compare the strings using equals.

In your case, if two instances of MyClass really are considered equal if the strings match, then:

public boolean equals(Object object2) {
    return object2 instanceof MyClass && a.equals(((MyClass)object2).a);
}

...but usually if you are defining a class, there's more to equivalency than the equivalency of a single field (a in this case).


Side note: If you override equals, you almost always need to override hashCode. As it says in the equals JavaDoc:

> Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Solution 2 - Java

You should override equals

 public boolean equals (Object obj) {
     if (this==obj) return true;
     if (this == null) return false;
     if (this.getClass() != obj.getClass()) return false;
     // Class name is Employ & have lastname
     Employe emp = (Employee) obj ;
     return this.lastname.equals(emp.getlastname());
 }

Solution 3 - Java

The best way to compare 2 objects is by converting them into json strings and compare the strings, its the easiest solution when dealing with complicated nested objects, fields and/or objects that contain arrays.

sample:

import com.google.gson.Gson;


Object a = // ...;
Object b = //...;
String objectString1 = new Gson().toJson(a);
String objectString2 = new Gson().toJson(b); 

if(objectString1.equals(objectString2)){
    //do this
}

Solution 4 - Java

The overwrite function equals() is wrong. The object "a" is an instance of the String class and "object2" is an instance of the MyClass class. They are different classes, so the answer is "false".

Solution 5 - Java

It looks like equals2 is just calling equals, so it will give the same results.

Solution 6 - Java

Your equals2() method always will return the same as equals() !!

Your code with my comments:

public boolean equals2(Object object2) {  // equals2 method
    if(a.equals(object2)) { // if equals() method returns true
        return true; // return true
    }
    else return false; // if equals() method returns false, also return false
}

Solution 7 - Java

Statements a == object2 and a.equals(object2) both will always return false because a is a string while object2 is an instance of MyClass

Solution 8 - Java

Your implementation must like:

public boolean equals2(Object object2) {
    if(a.equals(object2.a)) {
        return true;
    }
    else return false;
}

With this implementation your both methods would work.

Solution 9 - Java

Your class might implement the Comparable interface to achieve the same functionality. Your class should implement the compareTo() method declared in the interface.

public class MyClass implements Comparable<MyClass>{
    
    String a;
    
    public MyClass(String ab){
        a = ab;
    }
  
    // returns an int not a boolean
    public int compareTo(MyClass someMyClass){ 

        /* The String class implements a compareTo method, returning a 0 
           if the two strings are identical, instead of a boolean.
           Since 'a' is a string, it has the compareTo method which we call
           in MyClass's compareTo method.
        */

        return this.a.compareTo(someMyClass.a);
        
    }

    public static void main(String[] args){
    
        MyClass object1 = new MyClass("test");
        MyClass object2 = new MyClass("test");

        if(object1.compareTo(object2) == 0){
            System.out.println("true");
        }
        else{
            System.out.println("false");
        }
    }
}

    

Solution 10 - Java

The "==" operator returns true only if the two references pointing to the same object in memory. The equals() method on the other hand returns true based on the contents of the object.

Example:

String personalLoan = new String("cheap personal loans");
String homeLoan = new String("cheap personal loans");
      
//since two strings are different object result should be false
boolean result = personalLoan == homeLoan;
System.out.println("Comparing two strings with == operator: " + result);
      
//since strings contains same content , equals() should return true
result = personalLoan.equals(homeLoan);
System.out.println("Comparing two Strings with same content using equals method: " + result);
      
homeLoan = personalLoan;
//since both homeLoan and personalLoan reference variable are pointing to same object
//"==" should return true
result = (personalLoan == homeLoan);
System.out.println("Comparing two reference pointing to same String with == operator: " + result);

Output: Comparing two strings with == operator: false Comparing two Strings with same content using equals method: true Comparing two references pointing to same String with == operator: true

You can also get more details from the link: http://javarevisited.blogspot.in/2012/12/difference-between-equals-method-and-equality-operator-java.html?m=1

Solution 11 - Java

If you dont need to customize the default toString() function, another way is to override toString() method, which returns all attributes to be compared. then compare toString() output of two objects. I generated toString() method using IntelliJ IDEA IDE, which includes class name in the string.

public class Greeting {
private String greeting;

@Override
public boolean equals(Object obj) {
    if (this == obj) return true;
    return this.toString().equals(obj.toString());
}

@Override
public String toString() {
    return "Greeting{" +
            "greeting='" + greeting + '\'' +
            '}';
}
}

Solution 12 - Java

the return type of object.equals is already boolean. there's no need to wrap it in a method with branches. so if you want to compare 2 objects simply compare them:

boolean b = objectA.equals(objectB);

b is already either true or false.

Solution 13 - Java

When we use == , the Reference of object is compared not the actual objects. We need to override equals method to compare Java Objects.

Some additional information C++ has operator over loading & Java does not provide operator over loading. Also other possibilities in java are implement Compare Interface .which defines a compareTo method.

Comparator interface is also used compare two objects

Solution 14 - Java

Here the output will be false , false beacuse in first sopln statement you are trying to compare a string type varible of Myclass type to the other MyClass type and it will allow because of both are Object type and you have used "==" oprerator which will check the reference variable value holding the actual memory not the actual contnets inside the memory . In the second sopln also it is the same as you are again calling a.equals(object2) where a is a varible inside object1 . Do let me know your findings on this .

Solution 15 - Java

IN the below code you are calling the overriden method .equals().

public boolean equals2(Object object2) { if(a.equals(object2)) { // here you are calling the overriden method, that is why you getting false 2 times. return true; } else return false; }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFastkowyView Question on Stackoverflow
Solution 1 - JavaT.J. CrowderView Answer on Stackoverflow
Solution 2 - Javauser5119219View Answer on Stackoverflow
Solution 3 - JavaJoeGView Answer on Stackoverflow
Solution 4 - JavaJesús Talavera PortocarreroView Answer on Stackoverflow
Solution 5 - JavaHew WolffView Answer on Stackoverflow
Solution 6 - JavajlordoView Answer on Stackoverflow
Solution 7 - Javaashish.alView Answer on Stackoverflow
Solution 8 - JavaAzhar KhanView Answer on Stackoverflow
Solution 9 - Javatf3View Answer on Stackoverflow
Solution 10 - JavaMadhanView Answer on Stackoverflow
Solution 11 - JavaQinjieView Answer on Stackoverflow
Solution 12 - JavaCpt. MirkView Answer on Stackoverflow
Solution 13 - Javaumesh atadaView Answer on Stackoverflow
Solution 14 - JavaBidyadharView Answer on Stackoverflow
Solution 15 - JavaRamView Answer on Stackoverflow