虽然使用两个单独的数组并保持它们的排序同步是可能的,但使用这种类型的解决方案可能会导致难以在以后找到的错误。例如,如果数组之间的同步不正确,则可能会将错误的重量与身高匹配。
避免这种类型的问题的一种方法是封装身高/体重在一个类中,以便它们始终保持同步。在图1中,有一个名为Person
的类,它具有身高、体重和姓名作为属性。如果您总是按身高升序排序,则可以实现如图1所示的compareTo()
方法。
图2显示了一个junit测试用例,演示如何对Person
列表进行排序。测试用例还演示了如何按体重排序。在两种情况下,由于排序是在封装它们的对象上进行的,因此重量和身高之间永远不会出现同步问题。
图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");
}
}