TreeSet 排序

各种原因要做一些测试题....需要对Set排序,,我记得数组有排序,集合不知道有木有排序,,,打算自己写算法排序,,,查了查资料,TreeSet有排序功能...

题目如下


创建一个Student类,在Main方法中测试,创建10个不同的Students实例,将其放置到集合,且集合中的Students不能含有相同的值(StuName, StuNumber)不同,且将其按照年龄(age),由小到大的输出。
package com.memorycat.javasetest.question5;

import java.util.Comparator;

public class MyCompartor<T> implements Comparator<T>
{

	@Override
    public int compare(T arg0, T arg1)
    {
	    // TODO Auto-generated method stub
		
	    return ((Student)arg0).getAge() - ((Student)arg1).getAge();
    }

}



	public static void main(String[] args)
	{
		Student[] stu = new Student[10];
		stu[0] = new Student("小黑猫", "01", 13);
		stu[1] = new Student("MemoryCat", "03", 21);
		stu[2] = new Student("阿斯", "231", 12);
		stu[3] = new Student("额外", "223", 41);
		stu[4] = new Student("速度", "3521", 4);
		stu[5] = new Student("估计", "231", 27);
		stu[6] = new Student("斯蒂芬", "7541", 18);
		stu[7] = new Student("未米", "5471", 42);
		stu[8] = new Student("未范德萨", "341", 83);
		stu[9] = new Student("我憔悴", "231", 13);

		MyCompartor<Student> compartor = new MyCompartor<Student>();
		Set<Student> stus = new TreeSet<Student>(compartor);
		
		for (int i = 0; i < stu.length; i++)
		{
			stus.add(stu[i]);
		} 

		for (Student student : stus)
		{
			System.out.println(student);
		}

	}



结果如下


Student [StuName=速度, StuNumber=3521, age=4]
Student [StuName=阿斯, StuNumber=231, age=12]
Student [StuName=小黑猫, StuNumber=01, age=13]
Student [StuName=斯蒂芬, StuNumber=7541, age=18]
Student [StuName=MemoryCat, StuNumber=03, age=21]
Student [StuName=估计, StuNumber=231, age=27]
Student [StuName=额外, StuNumber=223, age=41]
Student [StuName=未米, StuNumber=5471, age=42]
Student [StuName=未范德萨, StuNumber=341, age=83]



评论
文章信息
作者: admin
目录: java
创建: 2014-07-31
更新: 2014-07-31
如果文章对你有帮助,请博主喝杯咖啡:-)