why equals() method when we have == operator? [dup

2019-01-01 16:24发布

This question already has an answer here:

When i see the implementation of equals() method it does nothing but same as what == does. So my question is what was the need to have this as separate method when we have == operator which does the same work?

8条回答
后来的你喜欢了谁
2楼-- · 2019-01-01 16:26

You can not overload the == operator, but you can override equals(Object) if you want it to behave differently from the == operator, i.e. not compare references but actually compare the objects (e.g. using all or some of their fields).

Also, if you do override equals(Object), have a look at hashCode() as well. These two methods need to be compatible (i.e. two objects which are equal according to equals(Object) need to have the same hashCode()), otherwise all kinds of strange errors will occur (e.g. when adding the objects to a set or map).

查看更多
不再属于我。
3楼-- · 2019-01-01 16:29

== compares object references, and asks whether the two references are the same.

equals() compares object contents, and asks whether the objects represent the same concept.

查看更多
栀子花@的思念
4楼-- · 2019-01-01 16:32

That's done so to make this possible:

String s1 = new String("foo");
String s2 = new String("foo");

System.out.println(s1 == s2); // false?! Different references!
System.out.println(s1.equals(s2)); // true

If you check the source of String#equals(), you'll see that it has overridden the Object#equals() appropriately to compare each other's internal character array (the actual value). Many other classes have this method overridden as well.

查看更多
几人难应
5楼-- · 2019-01-01 16:32

"string" == "string" will return false "string".equals("string") will return true

With o1 == o2 you compare that the object 1 is the same object than o2 (by reference)

With o1.equals(o2), depending on the object the equals method is overriden and not implemented with something like "return o1 == o2"

For exemple you create 2 Set instances These 2 set objects are 2 different objects, you can add different elements in any of those. set1 == set2 will always return false but set1.equals(set2) will eventually return true if the set2 contains exactly the same elements that set1... and because equals method is overriden in the Set class...

Equals implementation for Set is:

      public boolean equals(Object o) {
        if (o == this)
           return true;

        if (!(o instanceof Set))
             return false;
        Set s = (Set) o;
        if (s.size() != c.size())
             return false;
        return containsAll(s); // Invokes safe containsAll() above
    }
查看更多
骚的不知所云
6楼-- · 2019-01-01 16:33

== operator is used to compare references.
equals() method is defined over object definition.

Dog d =new Dog();
Collar c =new Collar("Red");
 d.setCollar(c);
Dog d2=new Dog();
 Collar c2=new Collar("Red");
d2.setCollar(c2);

 d2.getCollar() ==d.getCollar()

would return false indicating that the the two dogs have two different collar object (items).they do not share the same collar.

d2.getCollar().equals(d.getCollar())

return true if the Collar is defined as [Collar are same if color of Collar are same] the two dogs have same colored collar.

   class Collar{
    String color="";
    public Collar(String p0){
    this.color=p0;
    }
    boolean equals(Object c){
      Collar other=(Collar)c;
      return  this.color.equals(other.getColor());
    }

    public String getColor(){
      return this.color;
    }
    }
查看更多
笑指拈花
7楼-- · 2019-01-01 16:39

In java equals operator(==) operates on data of two variables if the operands are of primitive data types. But if the operands are objects java compares them using references because it has no way to figure out to compare on which field or fields of the object.

So there is only one way to compare based on user defined fields and that is defined in the object by overriding equals() methods, since equals operator(==) cannot be overrided in java as java does not supports operator overriding.

As an example if you want to compare Employee on the basis of name you need to define it's logic by overriding equals method in Employee class as below:

public class Employee {
    private Integer id;
    private String name;

    @Override
    public boolean equals(Object obj) {
        Employee other = (Employee) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }


}
查看更多
登录 后发表回答