我有这门课:
public class Friend {
private String name;
private String location;
private String temp;
private String humidity;
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
我想根据用户输入的名称、位置、温度和湿度对列表进行排序。
EDIT:用户指定必须按哪个数据成员进行排序。
做到这一点最简单的方法是什么?
谢谢。
因为您想按四种不同的标准对它们进行排序,所以实现 Comparable 是没有意义的。在这种情况下,您可能会发现为每个排序依据参数创建不同的比较器。但是,您可以为最符合逻辑的排序依据字段(例如名称)实现 Comparable。否则,比较器就是最佳选择。
public class FriendNameComparator extends Comparator<Friend> {
// assuming both are non-null for code simplicity; you may wish to change that
public int compare(Friend f1, Friend f2) {
return f1.getName().compareTo(f2.getName());
}
}
public class FriendLocationComparator extends Comparator<Friend> {
// assuming both are non-null for code simplicity; you may wish to change that
public int compare(Friend f1, Friend f2) {
return f1.getLocation().compareTo(f2.getLocation());
}
}
// and so forth
然后,您可以使用 Collections 实用程序类的排序函数按给定的比较器进行排序。
Collections.sort(friendsList, new FriendNameComparator()); // sorts by name
Collections.sort(friendsList, new FriendLocationComparator()); // sorts by location
// etc
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)