Java 21的新Sequence接口是什么?

huangapple go评论102阅读模式
英文:

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以获取该项的完整描述。Java 21的新Sequence接口是什么?

英文:

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.Java 21的新Sequence接口是什么?

huangapple
  • 本文由 发表于 2023年8月9日 12:16:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864541.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定