Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override equals() in Java

I am attempting to understand how "equals()" works in Java. Especially in contrast to "toString()". Here is an example that is throwing me off course.


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

Here nC1.print() and nC2.print() behaves as expected. Prints:

This is a car. Make: toyota | Model: corolla
This is a car. Make: toyota | Model: corolla

However nC1.equals( nC2 ), prints:

"They are NOT equal!"

In short the question is that I can override "toString()", but not "equals()". What am I missing? I presume there is a simple explanation for this behavior.

like image 684
John Smith Avatar asked Sep 23 '26 02:09

John Smith


1 Answers

I think you should keep the signature of the method as:

public boolean equals(Object obj)

As a side note: put @Override annotation within the method you want to override to make sure that you are overriding the right method, otherwise the compiler complains.

like image 106
Eng.Fouad Avatar answered Sep 24 '26 23:09

Eng.Fouad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!