您的位置:首页 > 其它

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

2013-07-07 11:16 489 查看

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

分类: Java学习类2009-07-31 09:04 2254人阅读 评论(0) 收藏 举报
stringobjectclassimport

我想熟悉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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: