【java】TreeSet的定制排序

package collection;

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

import org.junit.Test;

/*
 * TreeSet的定制排序
 */

public class TestTreeSet02 {
	// 主方法
	public static void main(String[] args) {

	}
	@Test
	//测试方法一
	public void test1(){
		// 1,创建一个Comparator接口的实现类对象(匿名方式)
		Comparator com = new Comparator() {
			// 重写compare方法
			public int compare(Object o1, Object o2) {
				// 在compare方法中,传入自定义对象x,并指定是由x的哪一个具体属性做判断来排序
				//if(o1 instanceof Fruit && o2 instanceof Fruit)
				Fruit f1 = (Fruit) o1;
				Fruit f2 = (Fruit) o2;
				int result;
				result = f1.getNum() > f2.getNum() ? 1 : (f1.getNum() == f2
						.getNum() ? 0 : -1);
				if (result == 0) {
					result = f1.getKind().compareTo(f2.getKind());
				}
				return result;
			}
		};
		// 2,将上一步创建好的Comparable实现类对象com传入TreeSet()构造器
		TreeSet ts = new TreeSet(com);
		// 添加Comparable接口中compare方法中对应类型的对象
		ts.add(new Fruit(5, "Apple"));
		ts.add(new Fruit(6, "Banana"));
		ts.add(new Fruit(6, "Pear"));
		//ts.add(new Person(1001,"zhangsan",28));
		// 增强for循环遍历一下集合
		for (Object obj : ts) {
			System.out.println(obj);
		}		
	}

}

// 自定义类Fruit
class Fruit {
	private int num;
	private String kind;

	public Fruit() {
	}

	public Fruit(int num, String kind) {
		this.num = num;
		this.kind = kind;
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public String getKind() {
		return kind;
	}

	public void setKind(String kind) {
		this.kind = kind;
	}

	@Override
	public String toString() {
		return "Fruit [num=" + num + ", kind=" + kind + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((kind == null) ? 0 : kind.hashCode());
		result = prime * result + num;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Fruit other = (Fruit) obj;
		if (kind == null) {
			if (other.kind != null)
				return false;
		} else if (!kind.equals(other.kind))
			return false;
		if (num != other.num)
			return false;
		return true;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值