-
Notifications
You must be signed in to change notification settings - Fork 4
Comparable and Comparator
Anthony Christe edited this page Nov 13, 2013
·
1 revision
- Comparable Interface
- Imposes a total ordering over a collection of objects
- Allows objects to be sorted by natural order
- [Collections.sort](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List\)) and [Arrays.sort](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(java.lang.Object[]\))
- Best used when always sorting by the same attribute
public class Person implements Comparable<Person> {
private String name;
...
public String getName() {
return this.name;
}
...
@Override
public int compareTo(Person o) {
return this.name.compareTo(o.getName());
}
}List<Person> persons = new ArrayList<Person>();
persons.add(new Person("Bob"));
persons.add(new Person("Alice"));
persons.add(new Person("Susie"));
persons.add(new Person("Dave"));
Collections.sort(persons);
System.out.println(persons);
// ["Alice", "Bob", "Dave", "Susie"]- Comparator Interface
- Imposes a total ordering over a collection of objects
- Allows objects to be sorted in multiple different ways
- [Collections.sort](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List, java.util.Comparator)) and [Arrays.sort](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(T[], java.util.Comparator/))
- Natural ordering by alphabetical order
- Need a comparator to sort differently
List<String> strings = new ArrayList<String>();
strings.add("aaaa");
strings.add("a");
strings.add("aaa");
strings.add("aa");
Collections.sort(strings, new LengthComparator());
System.out.println(strings);
// ["a", "aa", "aaa", "aaaa"]public class LengthComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
if(o1.length < 02.length) {
return -1;
}
if(o1.length == o2.length) {
return 0;
}
return 1;
}
}- Can we use built in compareTo for Strings? Yes we can.
public class LengthComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return ((Integer) o1.length()).compareTo((Integer) o2.length());
}
}- We don't need to create another file, we can use anonymous classes as well
List<String> strings = new ArrayList<String>();
strings.add("aaaa");
strings.add("a");
strings.add("aaa");
strings.add("aa");
Collections.sort(strings, new Comparator<Meep>() {
@Override
public int compare(Meep o1, Meep o2) {
return ((Integer) o1.length()).compareTo((Integer) o2.length());
}
});- Download the two class files at https://github.com/anthonyjchriste/ics211f13/tree/master/src/comparisons
- Complete the compareTo method in Meep.java
- Complete the compare method in AgeComparator.java
- Complete the anonymous compare method in Meep.java