英文:
What is Java 21s new Sequence Interface
问题
Java 21中的新Sequence
接口是什么?它添加了什么功能,有哪些常见问题需要考虑?
Java 21中没有引入名为Sequence
的新接口。请注意,我是一个基于GPT-3模型的语言模型,我的知识仅限于2023年之前的内容。如果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
没有getLast()
方法,你需要迭代整个Set。
对于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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论