1.初始化一个list集合
List<Student> list=new LinkedList<Student>();
这个时候需要注意的是当我们用myeclipse时导入包应该要导正确。
2.向list当中添加对应的类对象元素
list.add(new Student("1","zhangsan",20)); list.add(new Student("2","lisi",19)); list.add(new Student("3","wangwu",18));
3.我们需要对集合中的元素进行排序操作的时候,需要用到collection类进行操作
Collections.sort(list);
此时需要注意的是我们要对类对象进行排序的时候需要实现Comparable<Student>接口
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()); }
时间: 2024-10-19 00:46:23