如果只是单纯的字符串比较把SignBean类对象换成String对象道理都是一样的;
//定义数据源
List<SignBean> list = new ArrayList<>();
SignBean signBean = new SignBean();
signBean.setName("abc");
signBean.setValue("1");
list.add(signBean);
SignBean signBean1 = new SignBean();
signBean1.setName("abb");
signBean1.setValue("2");
list.add(signBean1);
SignBean signBean2 = new SignBean();
signBean2.setName("cb");
signBean2.setValue("3");
list.add(signBean2);
//排序
Collections.sort(list, new Comparator<SignBean>() {
@Override
public int compare(SignBean o1, SignBean o2) {
//拿到2个bean类中的name字符串进行比较,android中字符串比较是比较的ASCLL码
//compareTo() 字符串比较
int i = o1.getName().compareTo(o2.getName());
if (i > 0) {
return 1;
} else {
return -1;
}
}
});
for (int i = 0; i <list.size() ; i++) {
Log.e("tyl","name="+list.get(i).getName());
Log.e("tyl","value="+list.get(i).getValue());
}
//排序完成 打印数据结果:
name=abb
value=2
name=abc
value=1
name=cb
value=3
SignBean 类代码:
public class SignBean {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}