-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAboutComparison.java
More file actions
83 lines (67 loc) · 2.19 KB
/
AboutComparison.java
File metadata and controls
83 lines (67 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package intermediate;
import com.sandwich.koan.Koan;
import java.util.Arrays;
import java.util.Comparator;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.assertEquals;
public class AboutComparison {
@Koan
public void compareObjects() {
String a = "abc";
String b = "bcd";
assertEquals(a.compareTo(b), -1);
assertEquals(a.compareTo(a), 0);
assertEquals(b.compareTo(a), 1);
}
static class Car implements Comparable<Car> {
int horsepower;
// For an explanation for this implementation look at
// http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html#compareTo(T)
public int compareTo(Car o) {
return horsepower - o.horsepower;
}
}
@Koan
public void makeObjectsComparable() {
Car vwbeetle = new Car();
vwbeetle.horsepower = 50;
Car porsche = new Car();
porsche.horsepower = 300;
assertEquals(vwbeetle.compareTo(porsche), -250);
}
static class RaceHorse {
int speed;
int age;
@Override
public String toString() {
return "Speed: " + speed + " Age: " + age;
}
}
static class HorseSpeedComparator implements Comparator<RaceHorse> {
public int compare(RaceHorse o1, RaceHorse o2) {
return o1.speed - o2.speed;
}
}
static class HorseAgeComparator implements Comparator<RaceHorse> {
public int compare(RaceHorse o1, RaceHorse o2) {
return o1.age - o2.age;
}
}
@Koan
public void makeObjectsComparableWithoutComparable() {
RaceHorse lindy = new RaceHorse();
lindy.age = 10;
lindy.speed = 2;
RaceHorse lightning = new RaceHorse();
lightning.age = 2;
lightning.speed = 10;
RaceHorse slowy = new RaceHorse();
slowy.age = 12;
slowy.speed = 1;
RaceHorse[] horses = {lindy, slowy, lightning};
Arrays.sort(horses, new HorseAgeComparator());
assertEquals(horses[0], lightning);
Arrays.sort(horses, new HorseSpeedComparator());
assertEquals(horses[0], slowy);
}
}