List< String>的迭代与modyfing字符串 [英] Iteration of List<String> with modyfing String
本文介绍了List< String>的迭代与modyfing字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不能修改List的这种方式的元素:
for(String s:list)
{
s =x+ s;
}
执行后此列表的代码元素不变
如何 c ListIterator
接口:
for(int i = 0; i {
list.set(i,x+ list。 get(i));
}
for(ListIterator i = list.listIterator(); i.hasNext();)
{
i.set(x+ i。下一个());
}
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.
解决方案
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 the ListIterator
interface:
for (int i = 0; i < list.size(); i++)
{
list.set(i, "x" + list.get(i));
}
for (ListIterator i = list.listIterator(); i.hasNext(); )
{
i.set("x" + i.next());
}
这篇关于List< String>的迭代与modyfing字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文