将两个对象与. equals()和 = = 操作符进行比较

我用一个 String字段构造了一个类。然后我创建了两个对象,我必须使用 ==操作符和 .equals()对它们进行比较。我是这么做的:

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));
}




}

编译之后,结果显示两次 false。如果两个对象有相同的字段-“ test”,为什么是 false?

426434 次浏览

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
}

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

== 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.

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; }

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

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.

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

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.

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".

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());
}

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
}

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");
}
}
}

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

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 .

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 + '\'' +
'}';
}
}

In short, == compares two POINTERS.

If the two pointers are equal, then they both point to same object in memory (which, obviously has the same value as itself).

However, .equals will compare the VALUES of whatever is pointed to, returning true iff they both evaluate to the same value.
Thus, two separate strings (i.e., at different addresses in memory) are always != but are .equal iff they contain the same (null-terminated) sequence of chars.