往TreeSet中存入自定义对象,并且使用自定义排序方法(实现comparetor)

import java.util.*;
class Person implements Comparable
{
	private String name;
	private int age;
	Person(String name,int age)
	{
		this.name=name;
		this.age=age;
	}
	public int getAge()
	{
		return age;
	}
	public String getName()
	{
		return name;
	}
	public int compareTo(Object obj)
	{
		if (!(obj instanceof Person))
		{
			throw new RuntimeException("吊爆了!");
		}
		Person p=(Person)obj;
		if (this.age>p.age)
		{
			return 1;
		}
		if (this.age==p.age)
		{
			return this.name.compareTo(p.name);
		}
		return -1;
	}
}
class TreeSetTest
{
	public static void main(String[] args)
	{
		TreeSet t=new TreeSet(new Mycompare());
		t.add(new Person("xxc1",15));
		t.add(new Person("xxc2",20));
		t.add(new Person("xxc3",17));
		t.add(new Person("xxc4",16));
		t.add(new Person("xxc4",10));
		Iterator t1=t.iterator();
		while (t1.hasNext())
		{
			Person p=(Person)t1.next();
			System.out.println(p.getName()+"======"+p.getAge());
		}
	}
}
class Mycompare implements Comparator
{
	public int compare(Object o1,Object o2)
	{
		Person p=(Person)o1;
		Person p1=(Person)o2;
		int num=p.getName().compareTo(p1.getName());
		if (num==0)
		{
			return new Integer (p.getAge()).compareTo(new Integer(p1.getAge()));
		}
		return num;
		
		
		
		
		
		
		/*if (num>0)
		{
			return 1;
		}
		if (num==0)
		{
			if (p.getAge()>p1.getAge())
			{
				return 1;
			}
			if (p.getAge()==p1.getAge())
			{
				return 0;
			}
			if (p.getAge()<p1.getAge())
			{
				return -1;
			}
		}
		if (num<0)
		{
			return -1;
		}
		return num;*/
	}
}

TreeSet的第一种排序方式是实现Comparable接口覆写compareTo方法,此排序是自然顺序排序。

TreeSet的第二种排序方式是实现Comparator接口覆写compare方法,此排序是在集合一初始化就拥有的,所以要讲此接口的实例对象传入到TreeSet的构造函数中!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值