Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java why should equals method input parameter be Object

Tags:

java

types

equals

I'm going through a book on data structures. Currently I'm on graphs, and the below code is for the vertex part of the graph.

class Vertex<E>{
    //bunch of methods

    public boolean equals(Object o){
         //some code
    }
}

When I try to implement this equals method my compiler complains about not checking the type of the parameter and just allowing any object to be sent it. It also does seem a bit strange to me why that parameter shouldn't be a Vertex instead of an Object. Is there a reason why the author does this or is this some mistake or antiquated example?

like image 350
jhlu87 Avatar asked Jul 09 '11 19:07

jhlu87


People also ask

What is the type of parameter for equals method?

Parameter: This method accepts a mandatory parameter obj which is the object to be compared. Return Value: The method return true if Method object is same as passed object as parameter, otherwise false.

Can you use equals () on an Object?

The equals() method is a static method of the Objects class that accepts two objects and checks if the objects are equal. If both the objects point to null , then equals() returns true .

What is the purpose of the equals () method?

The equals() method compares two strings, and returns true if the strings are equal, and false if not.

Why do we need equals method in Java?

equals() is used to compare the two objects by some business logic and returns a boolean value. Use == operator when you want to compare the values of two primitive data types or you want to compare two references are same or not. Use . equals() method when you want to compare two objects by functionality.


1 Answers

@Override
public boolean equals(Object obj)
{
     if (!(obj instanceof Vertex)) return false;
     else return // blah blah
}
like image 129
Eng.Fouad Avatar answered Oct 03 '22 00:10

Eng.Fouad