1.初始化一个list集合eclipse
List<Student> list=new LinkedList<Student>();
这个时候须要注意的是当咱们用myeclipse时导入包应该要导正确。ide
2.向list当中添加对应的类对象元素this
list.add(new Student("1","zhangsan",20)); list.add(new Student("2","lisi",19)); list.add(new Student("3","wangwu",18));
3.咱们须要对集合中的元素进行排序操做的时候,须要用到collection类进行操做spa
Collections.sort(list);
此时须要注意的是咱们要对类对象进行排序的时候须要实现Comparable<Student>接口code
public class Student implements Comparable<Student> { private String Id; private String name; private int age; public Student(String id, String name, int age) { super(); Id = id; this.name = name; this.age = age; } public String getId() { return Id; } public void setId(String id) { Id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int compareTo(Student stu) { if(this.getAge()>stu.getAge()){ return 1; }else if(this.getAge()==stu.getAge()){ return 0; }else{ return -1; } } }
4.完成后就能够用foeach语句对集合内的元素进行迭代遍历对象
for(Student e:list){ System.out.println(e.getId()+" "+e.getName()+" "+e.getAge()); }