关键点:将List内存储的对象实现Comparable类,重写它的compareTo()方法即可
Bean:
package chc;
public class StuVo implements Comparable<StuVo>{
private String id;
private String name;
private Integer age;
public StuVo(String id, String name, Integer age) {
this.id=id;
this.name=name;
this.age=age;
}
public int compareTo(StuVo stu) {
return this.name.compareTo(stu.getName());
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Demo:
package chc;
import Java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class ArrayListSortDemo {
public static void main(String[] args) {
List<StuVo> stuList=new ArrayList<StuVo>();
StuVo stu=new StuVo("1","h小明",11);
stuList.add(stu);
stu=new StuVo("2","d阿熊",15);
stuList.add(stu);
stu=new StuVo("3","a张三",10);
stuList.add(stu);
stu=new StuVo("4","b李四",15);
stuList.add(stu);
Collections.sort(stuList);
Iterator<StuVo> it =stuList.iterator();
while(it.hasNext()){
System.out.println(it.next().getName());
}
}
}