java基础笔记(9)TreeSet,排序,map的遍历

每添加一个对象,都会调用hashcode方法
1.TreeSet
排好序的, 并且 不允许重复
set 无序并且不允许重复
tree底层利用的是红黑树
排序:
自定义的类
Integer
String
return 0 代表即将要添加的元素和现有的元素重复 则不添加
升序:this>o return 1
this<o return -1
降序 this>o return -1;
this<o return 1;
TreeSet 可以排序的, 泛型是自定义类的话 必须实现排序接口
Comparable 自然排序
2.自然排序

  1. 在泛型中的自定义类中实现Comparable<自定义类名>
  2. 重写compareTo方法
  3. 创建TreeSet集合,向集合中添加元素
    一个元素比较排序
public class Student implements Comparable<Student>{
   
	int age;
	public Student(int age) {
   
		super();
		this.age = age;
	}
	@Override
	public String toString() {
   
		return "Student [age=" + age + "]";
	}
	@Override
	public int compareTo(Student o) {
   		System.out.println("===compareTo===");
		if(this.age>o.age) {
   
			return -1;
		}else if (this.age<o.age) {
   
			return 1;
		}		
		return 0;
	}
}
public class Test {
   
	public static void main(String[] args) {
   
		TreeSet<Student> set = new TreeSet<>();
		set.add(new Student(5));
		set.add(new Student(33));
		set.add(new Student(1));
		set.add(new Student(6));
		set.add(new Student(6))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值