Consider the following incomplete declaration of a Name class for 2a-2c.
public class Name something missing
{
private String first;
private String last;
public Name(String firstName, String lastName)
{
first = firstName;
last = lastName;
}
//additional methods
}
2a) In the first two parts, you will modify the Name class so that it implements the Comparable interface. Show here what should go in place of something missing in the first line of the class declaration.
2b) In this part, implement the compareTo method. The standard ordering of names is to be used: alphabetical order by last name, and if the two last names are the same, alphabetical order by first name. Two names are considered the same if and only if both the first and last names are the same.
2c) Implement a toString method in the Name class, which takes no parameters and returns a String containing the full name: first name then last name. For example, if the first name is “John” and the last name is “Doe”, then toString should return “John Doe”.
public class Name implements Comparable<Name>
{
private String first;
private String last;
public Name(String firstName, String lastName)
{
first = firstName;
last = lastName;
}
@Override
public int compareTo(Name name){
int last = this.lastName.compareTo(name.lastName);
//Sort by last name, compareTo returns < 0 if this(keyword)
//is less than name, > 0 if this is
//greater than name and 0 if they are equal.
//Sort by first name if last names are same
return last == 0 ? this.firstName.compareTo(name.firstName) : last;
}
public String toString(){
return (first+" "+last);
}
}
Get Answers For Free
Most questions answered within 1 hours.