001package intermediate;
002
003import com.sandwich.koan.Koan;
004
005import java.util.Arrays;
006import java.util.Comparator;
007
008import static com.sandwich.koan.constant.KoanConstants.__;
009import static com.sandwich.util.Assert.assertEquals;
010
011public class AboutComparison {
012
013    @Koan
014    public void compareObjects() {
015        String a = "abc";
016        String b = "bcd";
017        assertEquals(a.compareTo(b), __);
018        assertEquals(a.compareTo(a), __);
019        assertEquals(b.compareTo(a), __);
020    }
021
022    static class Car implements Comparable<Car> {
023        int horsepower;
024
025        // For an explanation for this implementation look at
026        // http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html#compareTo(T)
027        public int compareTo(Car o) {
028            return horsepower - o.horsepower;
029        }
030
031    }
032
033    @Koan
034    public void makeObjectsComparable() {
035        Car vwbeetle = new Car();
036        vwbeetle.horsepower = 50;
037        Car porsche = new Car();
038        porsche.horsepower = 300;
039        assertEquals(vwbeetle.compareTo(porsche), __);
040    }
041
042    static class RaceHorse {
043        int speed;
044        int age;
045
046        @Override
047        public String toString() {
048            return "Speed: " + speed + " Age: " + age;
049        }
050    }
051
052    static class HorseSpeedComparator implements Comparator<RaceHorse> {
053        public int compare(RaceHorse o1, RaceHorse o2) {
054            return o1.speed - o2.speed;
055        }
056    }
057
058    static class HorseAgeComparator implements Comparator<RaceHorse> {
059        public int compare(RaceHorse o1, RaceHorse o2) {
060            return o1.age - o2.age;
061        }
062    }
063
064    @Koan
065    public void makeObjectsComparableWithoutComparable() {
066        RaceHorse lindy = new RaceHorse();
067        lindy.age = 10;
068        lindy.speed = 2;
069        RaceHorse lightning = new RaceHorse();
070        lightning.age = 2;
071        lightning.speed = 10;
072        RaceHorse slowy = new RaceHorse();
073        slowy.age = 12;
074        slowy.speed = 1;
075
076        RaceHorse[] horses = {lindy, slowy, lightning};
077
078        Arrays.sort(horses, new HorseAgeComparator());
079        assertEquals(horses[0], __);
080        Arrays.sort(horses, new HorseSpeedComparator());
081        assertEquals(horses[0], __);
082    }
083}