SE450: The Comparable Interface Type [15/41] Previous pageContentsNext page

file:horstmann/ch04_sort1/Country.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
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package horstmann.ch04_sort1;
/**
   A country with a name and area.
 */
public class Country implements Comparable<Country>
{
  /**
      Constructs a country.
      @param aName the name of the country
      @param anArea the area of the country
   */
  public Country(String aName, double anArea)
  {
    name = aName;
    area = anArea;
  }

  /**
      Gets the name of the country.
      @return the name
   */
  public String getName()
  {
    return name;
  }

  /**
      Gets the area of the country.
      @return the area
   */
  public double getArea()
  {
    return area;
  }


  /**
      Compares two countries by area.
      @param other the other country
      @return a negative number if this country has a smaller
      area than otherCountry, 0 if the areas are the same,
      a positive number otherwise
   */
  public int compareTo(Country other)
  {
    if (area < other.area) return -1;
    if (area > other.area) return 1;
    return 0;
  }

  private String name;
  private double area;
}

file:horstmann/ch04_sort1/CountrySortTester.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
package horstmann.ch04_sort1;
import java.util.ArrayList;
import java.util.Collections;

public class CountrySortTester
{
  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));

    Collections.sort(countries);
    // Now the array list is sorted by area
    for (Country c : countries)
      System.out.println(c.getName() + " " + c.getArea());
  }
}

Previous pageContentsNext page