Set
Set接口比Collection接口多了Set.of和Set.copyOf静态工厂方法
它们提供了创建不可修改集的便捷方法
但是,如果包含的元素本身是可变的,则可能导致Set表现不一致或其内容似乎发生变化。
Set为什么把从Collection继承的抽象方法又重新写了一遍
文档有说明
The
Set
interface places additional stipulations, beyond those inherited from theCollection
interface, on the contracts of all constructors and on the contracts of theadd
,equals
andhashCode
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]