TreeSet笔记02

package com.jenthor;

import java.util.*;

/*
 * 当元素自身不具备比较性,或者具备的比较性不是所需的、
 * 这时就让容器自身具备比较性。
 * 定义了比较容器,将比较器对象作为参数传递给TreeSet集合的构造函数
 * 
 * 当两种排序都存在时,以比较器为主。
 * 
 * 定义一个类,实现Comparator接口,覆盖compare方法。
 * 
 * 
 * 
 */
public class TreeSetDemo2 {
	public static void main(String[] args) {
		TreeSet ts = new TreeSet(new Mycompare());
		ts.add(new Student("lisi02", 22));
		ts.add(new Student("lisi007", 20));
		ts.add(new Student("lisi09", 19));
		ts.add(new Student("lisi08", 18));
		ts.add(new Student("lisi08", 18));
		ts.add(new Student("lisi08", 18));

		Iterator in = ts.iterator();
		while (in.hasNext()) {
			Student s = (Student) in.next();
			System.out.println(s.getName() + "..." + s.getAge());
		}
	}
}

class Mycompare implements Comparator {
	public int compare(Object o1, Object o2) {
		Student s1 = (Student) o1;
		Student s2 = (Student) o2;

		int num = s1.getName().compareTo(s2.getName());

		if (num == 0) {
		  return  new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
		   }
		return num;

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值