Introduction to the Comparable Interface

1. The Cow class implements the Comparable interface. The size of a cow is its weight. A default cow has a weight of 1800.

Given the following code:

public static void main(String[] args) {
    Cow[] cows = { new Cow(2000, "Hulk"),
                   new Cow(),
                   new Cow(1600, "Bessie"),
                   new Cow(1700, "Moohead"),
                   new Cow(),
                   new Cow(1900, "Big Time Jones") };

    printArray(cows);
    Arrays.sort(cows);
    printArray(cows);
}

the output should be:

Hulk, Anonymous Cow, Bessie, Moohead, Anonymous Cow, Big Time Jones, 
Bessie, Moohead, Anonymous Cow, Anonymous Cow, Big Time Jones, Hulk, 

Write the Cow class and printArray (which goes in the same class as main) and test it on the code, above to make sure it works.

 

2. Note that the class declaration can be done one of two ways:

public class Cow implements Comparable

and

public class Cow implements Comparable<Cow>

Which way is preferable and why?

 

3. Don't do this problem until the first two are done.

What happens if you remove the implements Comparable (or implements Comparable<Cow>) and then you run the program? Why does this happen?