简体   繁体   中英

Java - Is it possible for equals() to return false, even if contents of two Objects are same?

I know this is the duplicate question but that question was not asked correctly so I did not the get the answer. But I was being asked this question in one interview. I want to know is it possible? If yes, can anyone provide me the code how?

Thanks in advance.

StringBuilder does this as it's mutable. The contents are not considered, only whether the objects are the same.

StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
a.equals(b); // false as they are not the same object.

This is also true of all arrays which are objects

int[] a = {};
int[] b = {};
a.equals(b); // false, not the same object.
Arrays.equals(a, b); // true, contents are the same.

In java the method public boolean equals(Object obj) is inherited from the Object.class. Since all Java objects inherit (eventually) from Object, they all inherit that method as well. However, the implementation of the method as defined in the Object class is that the equals method will return if and only if the two objects being compared are the same instance.

public class WrappedString {
    private final String str = "hello";
}

public void foo() {
    WrappedString ws1 = new WrappedString();
    WrappedString ws2 = new WrappedString();
    System.out.println(ws1.equals(ws2));
}

The output of the above code snippet will be false since ws1 will only be equal to itself (eg other references to the same instance since equals is not overridden).

Yes, if you have a bad implementation of equals.

public boolean equals(Object o){
  return false;
}

For instance, or, if they don't have the exact same type:

public boolean equals(Object o){
  // o is an instance of a parent class, with exactly the same content. bad design, but possible.
  if ( o == null ){
    return false;
  }
  if ( !o.getClass().equals(this.getClass()){ // or a similar check
    return false;
  }
  Child ot = (Child)o;
  return this.content.equals(ot.getContent());
}

Yes. You can also override the equals() method and play with it.

class Person {
 private String Name;


 public Person(String name){
    this.name = name;
 }

 @Override
 public boolean equals(Object that){
  if(this == that) return false; //return false if the same address

  if(!(that instanceof People)) return true; //return true if not the same
  People thatPeople = (People)that;
  return !this.name.equals(thatPeople.name); //return false if the same name.
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM