[黑马程序员]集合--TreeSet

/*
 * Set:无序,不可以重复元素
 * |--HashSet:数据结构是哈希表。线程是非同步的
 * 			  保证元素唯一性的原理:判断元素的hashCode值是否相同。
 * 			 如果相同,会继续判断元素的equals方法是否为true。
 * |--TreeSet:可以对Set集合中的元素进行排序
 * 			  底层数据结构是二叉树
 * 			 保证元素唯一性的依据是: compareTo方法return的值。 正数,大,0,等,负数,小
 * 
 * 			TreeSet排序的第一种方式:让元素自身具备比较性。
 *          元素需要实现Comparable的接口,覆盖compareTo方法。
 *          这种方式也称为元素的自然排序,或者叫做默认顺序。
 * 
 * 
 * 
 * 
 * 需求:
 * 往 TreeSet集合中存储自定义对象学生,
 * 然后按照学生的年龄进行排序
 * 
 * 记住,排序时,当主要条件相同时,一定要判断次要条件
 */
package test.itheima;

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

public class TreeSetDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TreeSet<Student> ts = new TreeSet<Student>();

		ts.add(new Student("lisi22", 22));
		ts.add(new Student("lisi20", 20));
		ts.add(new Student("lisi40", 40));
		ts.add(new Student("lisi30", 30));
		ts.add(new Student("lisi36", 36));
		ts.add(new Student("lisi90", 90));
		ts.add(new Student("lisi50", 50));
		
		

		Iterator it = ts.iterator();

		while (it.hasNext()) {
			Student stu = (Student) it.next();
			System.out.println(stu.getName() + " .... " + stu.getAge());
		}

	}

}

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 this.name;
	}

	public int getAge() {
		return this.age;
	}

	@Override
	public int compareTo(Object o) {
		if (!(o instanceof Student)) {
			throw new RuntimeException("不是学生对象");

		}

		Student s = (Student) o;

		System.out.println(this.name + "---compare to---" + s.name);

		if (this.age != s.age) {
			System.out.println(this.age - s.age);
			return this.age - s.age;
		} else {
			// if(this.name.equals(s.name)){
			// return 0;
			// }
			// return 1;
			System.out.println("--- "+(this.name.compareTo(s.name)));
			return this.name.compareTo(s.name);
			
		}

	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值