, . , , .
- / , . 1 Person, , . , compareTo(), 1.
2 junit , Person s. , . , , .
1 - Person
public class Person implements Comparable {
private Float height;
private Float weight;
private String name;
public Person(){}
public Person(Float height, Float weight, String name) {
this.height = height;
this.weight = weight;
this.name = name;
}
public Float getHeight() {
return height;
}
public void setHeight(Float height) {
this.height = height;
}
public Float getWeight() {
return weight;
}
public void setWeight(Float weight) {
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int compareTo(Person other) {
return this.height.compareTo(other.getHeight());
}
}
2 - junit
import junit.framework.TestCase;
import java.util.*;
public class PersonTest extends TestCase {
private List personList = new ArrayList();
public PersonTest(String name) {
super(name);
}
public void testCompareTo() {
personList.add(new Person(72F,125F,"Bob"));
personList.add(new Person(69.9F,195F,"Jack"));
personList.add(new Person(80.05F,225.2F,"Joe"));
personList.add(new Person(57.02F,89.9F,"Sally"));
Collections.sort(personList);
assertEquals("Sally should be first (sorted by height asc)",personList.get(0).getName(),"Sally");
assertEquals("Jack should be second (sorted by height asc)",personList.get(1).getName(),"Jack");
assertEquals("Bob should be third (sorted by height asc)",personList.get(2).getName(),"Bob");
assertEquals("Joe should be fourth (sorted by height asc)",personList.get(3).getName(),"Joe");
Collections.sort(personList,new Comparator() {
public int compare(Person p1, Person p2) {
return p1.getWeight().compareTo(p2.getWeight());
}
});
assertEquals("Sally should be first (sorted by weight asc)",personList.get(0).getName(),"Sally");
assertEquals("Bob should be second (sorted by weight asc)",personList.get(1).getName(),"Bob");
assertEquals("Jack should be third (sorted by weight asc)",personList.get(2).getName(),"Jack");
assertEquals("Joe should be fourth (sorted by weight asc)",personList.get(3).getName(),"Joe");
}
}