的迭代与modyfing字符串

的迭代与modyfing字符串

本文介绍了List< String>的迭代与modyfing字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能修改List的这种方式的元素:

  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 unchangedHow 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&lt; String&gt;的迭代与modyfing字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 00:14