Java—即使两个对象的内容相同,equals()是否可能返回false?

Java—即使两个对象的内容相同,equals()是否可能返回false?,java,equals,Java,Equals,我知道这是一个重复的问题,但这个问题问得不对,所以我没有得到答案。 但我在一次采访中被问到这个问题。 我想知道这可能吗?如果是的话,谁能提供代码给我 提前谢谢 是的,如果equals的实现不好 public boolean equals(Object o){ return false; } 例如,或者,如果它们的类型不完全相同: public boolean equals(Object o){ // o is an instance of a parent class, with ex

我知道这是一个重复的问题,但这个问题问得不对,所以我没有得到答案。 但我在一次采访中被问到这个问题。 我想知道这可能吗?如果是的话,谁能提供代码给我


提前谢谢

是的,如果equals的实现不好

public boolean equals(Object o){
  return false;
}
例如,或者,如果它们的类型不完全相同:

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

在java中,
public boolean equals(Object obj)
方法是从Object.class继承的。由于所有Java对象(最终)都从对象继承,所以它们也都继承该方法。但是,对象类中定义的方法的实现是,当且仅当所比较的两个对象是同一实例时,
equals
方法才会返回

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

上述代码段的输出将为
false
,因为
ws1
将只等于其自身(例如,
equals
之后对同一实例的其他引用不会被覆盖)。

StringBuilder会这样做,因为它是可变的。不考虑内容,只考虑对象是否相同

StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
a.equals(b); // false as they are not the same object.
所有作为对象的数组也是如此

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

对。您还可以重写equals()方法并使用它

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

“我知道这是一个重复的问题,但这个问题问得不对,所以我没有得到答案。”好吧,没有。要么是重复的,在别处回答了,要么不是。你为什么要这样做?是的,您可以,您需要使用equals方法…这是最好的答案imho:使用Java标准库中的对象进行反例证明。