现在的位置: 首页 > 综合 > 正文

如何实现自定义类对象数组的排序

2017年12月15日 ⁄ 综合 ⁄ 共 1522字 ⁄ 字号 评论关闭

 

我想熟悉Arrays.sort()方法的朋友,无疑肯定是掌握了如何对基本类型的数组进行排如序,而在这里,我想说一下,如何对自定义类对象的数组进行排序?

例如,我定义一个Student类,拥有两个属性,即姓名(String name)和年龄(int age),如果现在我声明了一个Student类的对象数组,那么,如何利用Arrays.sort()方法对这个自定义对象数组加以排序呢?

其实,很简单,只需要做到以下3点即可:

首先,让需要进行排序的自定义类,如Student,去实现Comparable 接口

其次,重写Comparable接口唯一的方法:int compareTo(Object o)

最后,调用Arrays.sort()方法对自定义对象数组加以排序。

这里,我写了一个简单的程序加以说明,如下:

 

import java.util.Arrays;

 

public class Test {

    public static void main(String[] args) {

       Student[] myStudent = new Student[] { new Student("zhangsan", 22),

              new Student("lisi", 24), new Student("wangwu", 22),

              new Student("zhaoliu", 23) };

       System.out.println("----------before sorted---------");

       for (Student e : myStudent)

           System.out.println(e);

       System.out.println("/n/n----------after  sorted---------");

       Arrays.sort(myStudent);

       for (Student e : myStudent)

           System.out.println(e);

    }

}

 

class Student implements Comparable {

    private String name;

    private int age;

 

    public Student(String name, int age) {

       this.name = name;

       this.age = age;

    }

 

    public String toString() {

       return " Name:" + name + "/tage:" + age;

    }

 

    public int compareTo(Object o) {

       Student s = (Student) o;

       int result = age > s.age ? 1 : (age == s.age ? 0 : -1);

       if (result == 0) {

           result = name.compareTo(s.name);

       }

       return result;

 

    }

 

}

 

在此附上运行结果,以供参考,如下:

----------before sorted---------

 Name:zhangsan age:22

 Name:lisi age:24

 Name:wangwu  age:22

 Name:zhaoliu age:23

 

 

----------after  sorted---------

 Name:wangwu  age:22

 Name:zhangsan age:22

 Name:zhaoliu age:23

 Name:lisi age:24

 

 

 

 

抱歉!评论已关闭.