sorting names in java using comparable interface

2k Views Asked by At

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));
    }
}
2

There are 2 best solutions below

5
Peter Lawrey On BEST ANSWER

public String firstName() { return firstName; } //what is the use of this line

It's called a getter. It allows you to get the value while hiding the implementation from the calling code.

Name n = (Name) o; // why casting in n Name obj & also i did see anywhere call of this method

equals(Object) takes any object, however we need to see it as a Name so we can access it's fields/methods.

return 31*firstName.hashCode() + lastName.hashCode(); //what is this? i mean 31* , this line?

31 is 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.

public String toString() { //why this method is written, it is not called from aney where

Does it have to be? It might be called implicitly like

System.out.println(name); // calls toString()

public int compareTo(Name n) { //this method also not called from anywhere

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. ;)

3
Rod_Algonquin On
what this above program is doing?

It is a class that implements Comparable that will be used to sort your last name in ascending order with overridden equals, hashCode and toString method.

public int compareTo(Name n) {
    int lastCmp = lastName.compareTo(n.lastName);
    return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
}

For sorting the string the first line is to check if the value is greater or less than the compared string.

The second line is when the both last name are equal then it will sort the first name instead.

sample String

banana rod 
ras app 
apple rod 

it will be sorted as

ras app 
apple rod 
banana rod 

For the overriden toString()

When you print an Object of the name without overriding the toString

sample

 Name na = new Name();
 System.out.println(na);

It will print the memory location of that object in memory

and since it is overridden it it will print the first and last name.

For the overriden hashCode()

If you are trying to compare two Name object hashcode with the same last and first name they will return true.

sample:

 Name na = new Name();
 Name na2 = new Name();

 System.out.println(na.hashCode() == na2.hashCode()); //will return true if first and last name are the same