英文:
What is Java 21s new Sequence Interface
问题
在Java 21中,新的Sequence
接口是什么?它添加了什么,需要考虑哪些常见问题?
英文:
What is the new Sequence
interface in Java 21? What does it add and what may be common issues to consider?
答案1
得分: 3
Sequence
接口是Java对具有逻辑排序的连续Collections
的标准化,或者如JEP 431: Sequenced Collections所述,是“定义的遍历顺序”。SortedSet
能够保持其自然排序,List
保持其插入顺序等。
它添加的方法是:
SequencedCollection<E> reversed();
void addFirst(E);
void addLast(E);
E getFirst();
E getLast();
E removeFirst();
E removeLast();
getFirst()
方法可以替代list.get(0)
、deque.getFirst()
、sortedSet.first()
和linkedHashSet.iterator().next()
。getLast()
也一样,只是LinkedHashSet
没有获取最后一个元素的方法,您需要遍历整个集合。
对于SortedSet
来说,有一些奇怪之处,强制要求SortedSet
实现addFirst()
和addLast()
方法,在上下文中是没有意义的,而Jep说“这些方法可能会抛出UnsupportedOperationException
异常”。
Reversed()
也标准化了如何进行反向迭代。以前有navSet.descendingSet()
、deque.descendingIterator()
和for (var it = list.listIterator(list.size()); it.hasPrevious();) {}
等方法,再次强调LinkedHashSet
没有这个方法。现在reversed()
允许使用所有标准的迭代技巧,如for循环、流等,包括LinkedHashSet
。
最后需要注意的是,如果代码库使用了这些方法名,它们可能会遇到问题。请查看Jep以获取该项的完整描述。
英文:
The Sequence
interface is Java’s standardization of sequential Collections
that have a logical ordering, or as JEP 431: Sequenced Collections puts it, “a defined encounter order”. A SortedSet
would be able to keep its natural ordering, a List
keeps its insertion order etc.
The methods that it adds are
SequencedCollection<E> reversed();
void addFirst(E);
void addLast(E);
E getFirst();
E getLast();
E removeFirst();
E removeLast();
The getFirst()
method can replace list.get(0)
, deque.getFirst()
, sortedSet.first()
, and linkedHashSet.iterator().next()
. The same for getLast()
except LinkedHashSet
had no get last and you would have to iterate the entire Set.
There is some strangeness IMO to this regarding SortedSet
. SortedSet
is forced to implement the addFirst()
and addLast()
methods which don’t make sense in context and the Jep says “these methods can throw UnsupportedOperationException
”.
Reversed()
also standardizes how to iterate backwards. Previously, there was navSet.descendingSet()
, deque.descendingIterator()
, and for (var it = list.listIterator(list.size()); it.hasPrevious();)
and again
{}LinkedHashSet
has no method. Now reversed()
allows all the standard iteration techniques of fors, streams etc. and includes LinkedHashSet
.
One final note is that if a codebase used these method names they will run into issues. See the Jep for a full description of the item.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论