Java集合——Set、SortedSet

本文探讨Set接口的Set.of和Set.copyOf静态工厂方法,强调了在元素可变时可能带来的问题。同时介绍了SortedSet的特性,如Comparator使用和区间操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Set

Set接口比Collection接口多了Set.of和Set.copyOf静态工厂方法
它们提供了创建不可修改集的便捷方法
但是,如果包含的元素本身是可变的,则可能导致Set表现不一致或其内容似乎发生变化。

Set为什么把从Collection继承的抽象方法又重新写了一遍

文档有说明

The Set interface places additional stipulations, beyond those inherited from the Collection interface, on the contracts of all constructors and on the contracts of the add, equals and hashCode methods. Declarations for other inherited methods are also included here for convenience.

  • 添加对方法的实现额外的约定
  • 方便

Set的基本用法

Point[] points = {new Point(1, 1), new Point(2, 2), new Point(3, 3), };
Set<Point> st = Set.of(points);
System.out.println(Arrays.toString(st.toArray()));

// 对象是可变的
for (Point point : st) {
  point.x = 1;
  point.y = 1;
}

// 改变了对象的内容,导致不满足Set的定义
System.out.println(Arrays.toString(st.toArray()));// [(1.0, 1.0), (1.0, 1.0), (1.0, 1.0)]

SortedSet

Returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.

sortedSet要求元素必须可以转换为java.lang.Comparable类型

  • 可以为泛型参数T实现Comparable接口
  • 可以在构造方法传入一个匿名内部类实现Comparable接口(lambda也行)
SortedSet<Integer> sortedSet = new TreeSet<>((o1, o2) -> o2 - o1);
for (int i = 0; i < 10; i++) {
  sortedSet.add(i);
}
System.out.println(Arrays.toString(sortedSet.toArray()));
//返回比较器的地址,如果是自然比较顺序,返回null
System.out.println(sortedSet.comparator());//SetTest$$Lambda$54/0x0000000800bc7040@27f674d

SortedSet新增方法

SortedSet<Integer> sortedSet = new TreeSet<>();

for (int i = 0; i < 10; i++) {
  sortedSet.add(i);
}

Integer first = sortedSet.first();
Integer last = sortedSet.last();

// 所有小于5的元素
SortedSet<Integer> headSet = sortedSet.headSet(5);// [0, 1, 2, 3, 4]
System.out.println(Arrays.toString(headSet.toArray()));

// 所有大于等于5的元素
SortedSet<Integer> tailSet = sortedSet.tailSet(5);
System.out.println(Arrays.toString(tailSet.toArray()));//[5, 6, 7, 8, 9]

// 所有值在[formElement, toElement)区间内的元素
SortedSet<Integer> subSet = sortedSet.subSet(0, 8);
System.out.println(Arrays.toString(subSet.toArray()));//[0, 1, 2, 3, 4, 5, 6, 7]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值