自定义对象数组的排序

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

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

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

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

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

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

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




 

你可能感兴趣的:(自定义对象数组的排序)