我试图了解“equals()”在 Java 中的工作原理。尤其是与“toString()”相比。这是一个让我偏离正轨的例子。
public class Car
{
String make, model;
public Car( String model, String make )
{
this.make = model;
this.model = make;
}
public String toString()
{
String str = "This is a car. ";
str += "Make: " + make + " | Model: " + model;
return str;
}
public boolean equals( Car c )
{
return ( make.equals( c.make ) && model.equals( c.model ) );
}
}
public class Node
{
protected Object obj;
protected Node next;
public Node( Object o )
{
this.obj = o;
this.next = null;
}
public String toString()
{
return obj.toString();
}
public boolean equals( Node n )
{
return ( this.obj.equals( n.obj ) );
}
}
Car c1 = new Car("toyota", "corolla");
Car c2 = new Car("toyota", "corolla");
Node nC1 = new Node( c1 );
Node nC2 = new Node( c2 );
nC1.print();
nC2.print();
if( nC1.equals( nC2 ) )
System.out.println("They are equal!");
else
System.out.println("They are NOT equal!");
这里 nC1.print() 和 nC2.print() 的行为符合预期。印刷:
This is a car. Make: toyota | Model: corolla
This is a car. Make: toyota | Model: corolla
然而 nC1.equals( nC2 ),打印:
"They are NOT equal!"
简而言之,问题是我可以覆盖“toString()”,但不能覆盖“equals()”。我错过了什么?我认为这种行为有一个简单的解释。