`
ll_feng
  • 浏览: 383815 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java中对象数组的排序与比较

    博客分类:
  • j2se
 
阅读更多
首先,数组中的元素即被排序的对象要实现comparable接口及其compareTo(Object o)方法

class Student implements Comparable{

    int age;
    String name;
    public Student(int age,String name){
        this.age = age;
        this.name = name;
    }

    public int compareTo(Object o){
        Student s = (Student)o;
        return age>s.age ? 1 : (age==s.age ? 0 : -1);
    }
}


第二步,通过Arrays.sort(Object[] a) 对数据进行排序

Student[] students = Student[]{new Student(10,"zhangsan"),new Student(20,"lisi"),new Student(30,"wangwu")};
Arrays.sort(students);
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics