what is the use of equals,hashcode,toString methods in this below example? Can anyone please explain me in simple way with example for the same
import java.util.*;
//sort lists of comparable elements
public class Name implements Comparable<Name> {
private final String firstName, lastName;
public Name(String firstName, String lastName) {
if (firstName == null || lastName == null)
throw new NullPointerException();
this.firstName = firstName;
this.lastName = lastName;
}
public String firstName() { return firstName; }
public String lastName() { return lastName; }
public boolean equals(Object o) {
if (!(o instanceof Name))
return false;
Name n = (Name) o;
return n.firstName.equals(firstName) && n.lastName.equals(lastName);
}
public int hashCode() {
return 31*firstName.hashCode() + lastName.hashCode();
}
public String toString() {
return firstName + " " + lastName;
}
public int compareTo(Name n) {
int lastCmp = lastName.compareTo(n.lastName);
return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
}
}
It's called a getter. It allows you to get the value while hiding the implementation from the calling code.
equals(Object) takes any object, however we need to see it as a
Nameso we can access it's fields/methods.31is a common prime number used in hash codes. By multiply the hashCode of one field by a number it means that if you swap the names around the hashCode won't be the same.Does it have to be? It might be called implicitly like
Perhaps it is not used. A common pattern for developers to implement methods which might be used but never are. Another approach is to follow YAGNI (You Aint Gonna Need It) and only implement method you know you need, not ones you can imagine.
For example, you might find that you need a comparator which sorts by first name, then last. Now you can't just make the class Comparable because it already is. You mgith change the compareTo but this might break some thing. If it is used, this is fairly easy to find and so you know you can't change it. However, it's harder to find something which is not there. i.e. proving it is never used and thus you can just change the method is harder.
It would have been much easier if methods not used were not added, then you know they are not used. ;)