Android-Collections.sort() 逃离我推掉我的手 2023-01-17 12:52 100阅读 0赞 将对象进行比较 但是对象中有多种属性 方法一: public class FriendInfo implements Comparable<Student> { private String name; private String pinyin; private String firstLetter; public String getFirstLetter() { return firstLetter; } public void setFirstLetter(String firstLetter) { this.firstLetter = firstLetter; } public FriendInfo() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPinyin() { return pinyin; } public void setPinyin(String pinyin) { this.pinyin = pinyin; } @Override public int compareTo(FriendInfoom f) { //通过首字符比较进行升序排序 return this.firstLetter - f.firstLetter; } @Override public String toString() { return "FriendEntity{" + "name='" + name + '\'' + ", pinyin='" + pinyin + '\'' + '}'; } } } /** * 测试代码 */ Collections.sort(list); 实现Comparable可以使对象可比较的 方法二: Collections.sort(friends, new Comparator<FriendInfo>() { @Override public int compare(FriendInfo f1, FriendInfo f2) { if (f1.getFirstLetter().contains("#")) { return 1; } else if (f2.getFirstLetter().contains("#")) { return -1; } else{ return f1.getFirstLetter().compareTo(f2.getFirstLetter()); } } }); 但是在jdk1.7版本以上,需要添加一条比对二者相等的情况,返回0,否则会报错 java.lang.IllegalArgumentException: Comparison method violates its general contract!
还没有评论,来说两句吧...