Java 21的新Sequence接口是什么?

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

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

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

发表评论

匿名网友

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

确定