Student类中有name和age属性,在List<Student>里存了几个Student对象,要求按照学生年龄的降序输出。请高手帮忙~

解决方案 »

  1.   

    Student类实现Comparable接口,按你的要求重写public int compareTo(T o);方法就可以直接利用Collections.sort(list)方法了。
      

  2.   

    写个Comparator, 根据年龄大小进行比较,然后
      

  3.   


    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;public class ListSort {
    private void sortByType(List<Student> list) {
    Collections.sort(list, new Comparator<Student>() {
    public int compare(Student o1, Student o2) {
    return o1.getAge()>o2.getAge()?1:0;
    }
            
            });
    } public static void main(String[] args) {
    List<Student> list = new ArrayList<Student>();
    Student student1 = new Student(23, "小明");
    Student student2 = new Student(12, "小刘");
    Student student3 = new Student(7, "小张");
    list.add(student1);
    list.add(student2);
    list.add(student3);

    ListSort listSort = new ListSort();
    listSort.sortByType(list);

            for(Student student : list) {
             System.out.println(student.getAge()+"\t"+student.getName());
            }
    } public static class Student {
            int age;
    String name;

    public Student(int age, String name) {
    super();
    this.age = age;
    this.name = name;
    } public int getAge() {
    return age;
    } public void setAge(int age) {
    this.age = age;
    } public String getName() {
    return name;
    } public void setName(String name) {
    this.name = name;
    }

    }
    }
      

  4.   

    能不能在写查询语句的时候order by 年龄?
      

  5.   


    so quickly!!package test;import java.util.Arrays;public class Student implements Comparable<Student>{ private String name; private int age; public Student(String name,int age){
    this.age = age;
    this.name = name;
    }
    public int getAge() {
    return age;
    } public void setAge(int age) {
    this.age = age;
    } public String getName() {
    return name;
    } public void setName(String name) {
    this.name = name;
    } public int compareTo(Student o) {
    // TODO Auto-generated method stub
    if(this.age>o.age)
    return -1;
    else if(this.age<o.age)
    return 1;
    else
    return 0;
    }

    public String toString(){
    return "name:"+name+",age:"+age;
    }

    public static void main(String[] args) {
    Student [] sts = new Student[5];
    sts[0] = new Student("aaaa",13); 
    sts[1] = new Student("bbbb",18);
    sts[2] = new Student("cccc",68);
    sts[3] = new Student("dddd",2);
    sts[4] = new Student("eeee",5);
    Arrays.sort(sts);
    for(Student s:sts)
    System.out.println(s);
    }}