List的迭代使用 modyfing 字符串
我无法以这种方式修改列表的元素:
for (String s : list)
{
s = "x" + s;
}
执行此代码后,该列表的元素不会更改 如何用最简单的方式通过List实现modyfing的迭代。
I can't modyfing element of List this way:
for (String s : list)
{
s = "x" + s;
}
After execution this code elements of this list are unchanged
How to achieve iteration with modyfing through List in the simplest way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
由于
String
对象是不可变的,因此您无法更改正在迭代的值。此外,您无法修改在这样的循环中迭代的列表。执行此操作的唯一方法是使用标准循环迭代列表索引或使用ListIterator
接口:Since
String
objects are immutable, you cannot change the values you're iterating over. Furthermore, you cannot modify the list you're iterating over in such a loop. The only way to do this is to iterate over the list indexes with a standard loop or to use theListIterator
interface:字符串是不可变的野兽,因此我建议遵循这一理念并创建新列表而不是修改列表:
我相信,这将使您的代码更易于理解和维护。
Strings are immutable beasts, so I can recommend to follow this philosophy and create new list instead modifying one:
I believe, that this will make your code easier to understand and maintain.
像这样的事情应该可以完成这项工作:
Something like this should do the job:
Java 字符串是不可变的,因此无法修改。此外,如果您希望修改列表,请使用迭代器接口。
Java strings are immutable, hence they cannot be modified. Further, if you wish to modify a list use the iterator interface.
正如其他人指出的那样:
s = "x" + s
将创建一个新字符串(不会包含在列表中)s
是局部变量,分配给它时,不会影响列表中包含的值。在这种情况下,解决方案是使用
StringBuilder
来表示您可以实际修改的字符串,或者使用ListIterator
作为 @Michael Borgwardt @jarnbjo 指出。使用
StringBuilder
:使用
ListIterator
:ideone.com 演示
As others have pointed out:
s = "x" + s
will create a new string (which will not be contained in the list)s
is a local variables, which, when assigned to, does not affect the values contained in the list.The solution is in this case to use a
StringBuilder
which represents a string which you can actually modify, or to use aListIterator
as @Michael Borgwardt and @jarnbjo points out.Using a
StringBuilder
:Using a
ListIterator
:ideone.com demo
在循环中,您只是修改字符串的本地副本。更好的选择是使用列表的迭代器,并替换列表的当前位置。
编辑,哎呀,速度太慢了。
In your loop you're just modifying the local copy of the String. A better alternative would be to use the iterator of the list, and replace the current position of the list.
Edit, Oops, way to slow.
您无法以这种方式修改
List
的String
元素,但StringBuilder
可以正常工作:对于其他基元也是如此对比参考情况和 for-each 循环。在循环中,
Iterable
是不可变的,但其中项的状态不是 - 基元(如String
)没有状态,因此您只需修改一个本地副本,但引用可以有状态,因此您可以通过它们可能具有的任何变异方法(例如,sb.append("x")
)来改变它们。You can't modify a
String
element of aList
that way, but aStringBuilder
would work just fine:The same is true for other primitive vs reference situations and the for-each loop. In the loop, the
Iterable
is immutable, but the state of items in it is not - primitives (likeString
) do not have state and hence you're only modifying a local copy, but references can have state and hence you can mutate them via any mutator methods they might have (e.g.,sb.append("x")
).另一种选择是使用
replaceAll()
Another option, use
replaceAll()