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?
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.
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 .
The equals() method compares two strings, and returns true if the strings are equal, and false if not.
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.
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof Vertex)) return false;
else return // blah blah
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With