集合TreeSet

/*
Set:无序,不可以重复元素
	|--Hashset: 数据结构是哈希表,线程是非同步的。
				保证元素唯一性的原理:判断元素的hashCode值是否相同
				如果相同,还会继续判断元素的equals方法,是否为true.
	|--TreeSet:可以对Set集合中的元素进行排序。
				底层数据结构是二叉树。
				保证元素唯一性的依据:compareTo方法

				TreeSet排序的第一种方式:让元素自身具备比较性。
				元素需要实现Comparable接口,覆盖compareTo方法。
				此种方式也称为元素的自顺序,或者叫做默认顺序。
				
				TreeSet的第二种排序方式:
				当元素自身不具备比较性时,或者具备的比较性不是所需要的
				这时就需要让集合自身具备比较性。
				在集合初始化时,就有了比较方式。
需求:
	往TreeSet集合中存储自定义对象学生。
	想按照学生的年龄进行排序。
*/
import java.util.*;

class  SetDemo
{
	public static void main1(String[] args) 
	{
		TreeSet ts = new TreeSet();
		ts.add("java1");
		ts.add("c");
		ts.add("c++");
		ts.add("java");

		Iterator it = ts.iterator();
		while(it.hasNext())
			System.out.println(it.next());
	}

	public static void main(String[] args) 
	{
		TreeSet ts = new TreeSet();
		/* 
		往TreeSet集合中存入对象是要排序的,但是如果我们不告诉TreeSet对象如何
		排序,TreeSet 会出错。所以往 TreeSet集合中 存入的对象要具有比较性。

		Exception in thread "main" java.lang.ClassCastException: 
		Student cannot be cast to java.lang.Comparable
		public interface Comparable<T>:此接口强行对实现它的每个类的对象进行整体排序。
		这种排序被称为类的自然排序,类的 compareTo 方法被称为它的自然比较方法。
		
		当对象没有实现 接口 Comparable 时,使用下面的方法,会打上面的Exception a
		异常。
		ts.add(new Student("sh3",23));
		ts.add(new Student("sh4",24));
		ts.add(new Student("sh1",21));
		ts.add(new Student("sh2",22));

		*/
		ts.add(new Student("sh3",23));
		ts.add(new Student("sh4",24));
		ts.add(new Student("sh1",21));
		ts.add(new Student("sh2",22));
		ts.add(new Student("sh5",22));

		Iterator it = ts.iterator();
		while(it.hasNext())
		{
			Student sd = (Student)it.next();
			System.out.println("name:"+sd.getName()+" age:"+sd.getAge());
		}
	}
}

/*
往TreeSet集合中存入对象是要排序的,但是如果我们不告诉TreeSet对象如何
排序,TreeSet 会出错。所以往 TreeSet集合中 存入的对象要具有比较性。
该要实现Comparable接口。
*/
//class Student //存入TreeSet集合中的对象要具备比较性,要实现 Comparable接口
class Student implements Comparable
{
	private String name;
	private int age;
	Student(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
	
	//自动调用
	public int compareTo(Object obj)
	{
		if(!(obj instanceof Student))
		{
			throw new RuntimeException("对象转换不成功!");
		}
		Student s = (Student)obj;
		if(this.age>s.age)
			return 1;
		else if(this.age == s.age)
		{
			//如果年龄相同,则再比较姓名
			return this.name.compareTo(s.name);
		}
		else
			return -1;

	
		
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值