JDK 21新特性---有序集合
概述
- 在JDK 21中,正式加入了序列集合的功能,新增了SequencedCollection,SequencedSet,SequencedMap接口,使得Java中的有序集合类可以按照统一的方法来进行集合的操作。
- 架构图:
三大接口
-
SequencedCollection
interface SequencedCollection<E> extends Collection<E> { SequencedCollection<E> reversed(); // methods promoted from Deque void addFirst(E); void addLast(E); E getFirst(); E getLast(); E removeFirst(); E removeLast(); }
-
SequencedSet
```java interface SequencedSet<E> extends Set<E>, SequencedCollection<E> { SequencedSet<E> reversed(); // covariant override } ```
-
SequencedMap
interface SequencedMap<K,V> extends Map<K,V> { SequencedMap<K,V> reversed(); SequencedSet<K> sequencedKeySet(); SequencedCollection<V> sequencedValues(); SequencedSet<Entry<K,V>> sequencedEntrySet(); V putFirst(K, V); V putLast(K, V); // methods promoted from NavigableMap Entry<K, V> firstEntry(); Entry<K, V> lastEntry(); Entry<K, V> pollFirstEntry(); Entry<K, V> pollLastEntry(); }
示例
List<Integer> originalList = Lists.newArrayList(1, 2, 3, 4, 5);
List<Integer> reversedList=originalList.reversed();
System.out.println("original list : " + originalList);
System.out.println("reversed list : " + reversedList);
originalList.addLast(6);
System.out.println("modified original list : " + originalList);
System.out.println("modified reversed list : " + reversedList);
SequencedMap<String,Integer> sequencedMap=Maps.newLinkedHashMap();
sequencedMap.put("a",1);
sequencedMap.put("b",2);
Map.Entry<String,Integer> firstEntry=sequencedMap.entrySet().iterator().next();
System.out.println("map first value : "+firstEntry.getValue());
firstEntry.setValue(100);
System.out.println("modified map first value : "+firstEntry.getValue());
Map.Entry<String,Integer> firstEntry2=sequencedMap.firstEntry();
System.out.println("map first value : "+firstEntry2.getValue());
//抛出UnsupportedOperationException
firstEntry2.setValue(200);