如何迭代SortedSet来修改其中的项目 [英] How to iterate over a SortedSet to modify items within
问题描述
假设我有一个列表。在for循环中修改list的项目没有问题:
lets say I have an List. There is no problem to modify list's item in for loop:
for (int i = 0; i < list.size(); i++) { list.get(i).setId(i); }
但我有一个SortedSet而不是list。我怎么能用它呢?
谢谢
But I have a SortedSet instead of list. How can I do the same with it? Thank you
推荐答案
首先,设置
假设它的元素是不可变的(实际上,可变元素是允许的,但它们必须遵守一个非常具体的合同,我怀疑你的班级会这样做。)
First of all, Set
assumes that its elements are immutable (actually, mutable elements are permitted, but they must adhere to a very specific contract, which I doubt your class does).
这意味着通常你不能像使用列表那样就地修改set元素。
This means that generally you can't modify a set element in-place like you're doing with the list.
a <$的两个基本操作c $ c>设置支持是添加和删除元素。修改可以被认为是删除旧元素,然后添加新元素:
The two basic operations that a Set
supports are the addition and removal of elements. A modification can be thought of as a removal of the old element followed by the addition of the new one:
- 你可以照顾通过使用
Iterator.remove()
; - 您可以在单独的容器中累积添加内容并调用< a href =http://docs.oracle.com/javase/6/docs/api/java/util/Set.html#addAll%28java.util.Collection%29 =nofollow>
最后设置.addAll()
。
- You can take care of the removals while you're iterating, by using
Iterator.remove()
; - You could accumulate the additions in a separate container and call
Set.addAll()
at the end.
这篇关于如何迭代SortedSet来修改其中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!