Reputation: 1
While Comparable is supposed to capture the natural ordering for a class, it's possible to imagine unnatural orderings as well. So: in the box provided below, reimplement the compareTo() method so that one Infant is less than another, if the length of his or her name is less than the other.
public class Infant implements Comparable {
private String name;
private int age; // in months
public Infant(String who, int months) {
name = who;
age = months;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void anotherMonth() {
age = age + 1;
}
This is what I have but I don't understand
public int compareTo(Object other) {
String b = ((Infant)other).getName();
String a = this.name;
return a.compareTo(b);
}
Upvotes: 0
Views: 2571
Reputation: 30310
It sounds like you want two orderings--the natural ordering and an alternative ordering. This is what Comparable
and Comparator
are for.
Now it is entirely up to you which is which, but let's just say I decide I want the natural order for an Infant
to be by age and the alternate order to be by length of name.
Then you could do this utilizing generics:
public class Infant implements Comparable<Infant> {
//Stuff
public int compareTo(Infant other) {
return new Integer(age).compareTo(other.age);
//or you can of course do the primitive comparisons but I'm lazy
//and don't hate autoboxing
}
}
And then you could also do this:
public class InfantNameLengthComparator implements Comparator<Infant> {
int compare(Infant first, Infant second) {
return new Integer(first.getName().length()).compareTo(second.getName().length());
}
}
And then you can sort in two ways:
Collections.sort(listOfInfants);
by age--the default, natural ordering
Collections.sort(listOfInfants, new InfantNameLengthComparator());
by length of name
You can even add other Comparator
s to do other alternative orderings like alphabetically by name while always preserving the natural order by age.
So you can use both Comparable
and Comparator
to provide both natural order and alternate order.
If you like, you can check out a tutorial we recently did on this exact subject.
Hope this helps.
Upvotes: 0
Reputation: 347194
compareTo
allows you to define the result of how two objects compare to each other...
So, for your example you could use...
public int compareTo(Object other) {
String b = ((Infant)other).getName();
String a = this.name;
return(a.length() - b.length());
}
Generally speaking, I would, personally, create "purpose" built Comparable
s that allow you to change the default behaviour as required.
So you could define a ByNameLengthComparable
and/or ByAgeComparable
that could be past to things like Arrays#sort
and Collections#sort
for example...
Upvotes: 2