为TreeSet集合增加比较器实现排序

package com.liangjing.set;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {             //main方法 
		// TODO Auto-generated method stub
		TreeSet set = new TreeSet(new MyComparator() {//构造方法内传递比较器实例
		});
//		set.add("C");
//		set.add("A");
//		set.add("B");
//		set.add("E");
//		set.add("F");
//		set.add("D");
		//实例化
		Student s1 = new Student(78);
		Student s2 = new Student(95);
		Student s3 = new Student(82);
		Student s4 = new Student(69);
		//加入集合
		set.add(s1);
		set.add(s2);
		set.add(s3);
		set.add(s4);
		
		
<span style="white-space:pre">		</span>//迭代器输出
		for (Iterator iter = set.iterator(); iter.hasNext();) {

//			String value = (Student)iter.next();
//			System.out.println(value);

			Student Student =(Student)iter.next();
			System.out.println(Student.score);      //直接打印Student输出也一样?
			
		}

	}

}

class Student {           //学生类
	int score;        //分数属性

	public Student(int score) {        // 构造方法
		this.score = score;
	}

	public String toString() {          //toString重写,此处不是必须
		return String.valueOf(this.score);
	}
}

class MyComparator implements Comparator {          //自定义比较器实现Comparator接口 compare方法,这里实现逆序
	public int compare(Object o1, Object o2) {

//		String s1 = (String) o1;
//		String s2 = (String) o2;
//		return s2.compareTo(s1);

		Student s1 =(Student)o1;          
		Student s2 =(Student)o2;
		return s2.score-s1.score;          //逆序

	}

}
输出 //注释部分输出 FEDCBA
95
82
78
69

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值