SE450: The Comparator interface type [17/41] Previous pageContentsNext page

file:horstmann/ch04_sort2/CountryComparatorByName.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
package horstmann.ch04_sort2;
import java.util.Comparator;

public class CountryComparatorByName implements Comparator<Country>
{
  public int compare(Country country1, Country country2)
  {
    return country1.getName().compareTo(country2.getName());
  }

}

file:horstmann/ch04_sort2/ComparatorTester.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
package horstmann.ch04_sort2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ComparatorTester
{
  public static void main(String[] args)
  {
    ArrayList<Country> countries = new ArrayList<Country>();
    countries.add(new Country("Uruguay", 176220));
    countries.add(new Country("Thailand", 514000));
    countries.add(new Country("Belgium", 30510));
    Comparator<Country>  comp = new CountryComparatorByName();
    Collections.sort(countries, comp);
    // Now the array list is sorted by area
    for (Country c : countries)
      System.out.println(c.getName() + " " + c.getArea());
  }
}

Previous pageContentsNext page