修改ArrayList的元素

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

Modify elements of an ArrayList

问题

public class Main {
    public static void main(String args[]){
        ArrayList<String> aList = new ArrayList<>();
        aList.add("aa");
        aList.add("bb");
        aList.add("cc");

        new Main().modifyList(aList);
        for(String s: aList){
            System.out.println(s);
        }
    }

    public void modifyList(ArrayList<String> aList){
        for(int i = 0; i < aList.size(); i++){
            String s = aList.get(i);
            System.out.println(s);
            s = s + "ss";
            aList.set(i, s);
        }
    }
}
英文:

For the below code, I was hoping that elements of my arraylist would be modified but its not. How can I modify the elements

public class Main {
    public static void main(String args[]){
        ArrayList&lt;String&gt; aList = new ArrayList&lt;&gt;();
        aList .add(&quot;aa&quot;);
        aList .add(&quot;bb&quot;);
        aList .add(&quot;cc&quot;);
        
        new Main().modifyList(aList );
        for(String s: aList ){
            System.out.println(s);
        }
    }
    
    public void modifyList(ArrayList&lt;String&gt; aList ){
        for(String s: aList){
            System.out.println(s);
            s = s + &quot;ss&quot;;
        }
    }
}

Its printing
aa
bb
cc
aa
bb
cc

Expected output
aa
bb
cc
aass
bbss
ccss

答案1

得分: 1

public void modifyList(ArrayList&lt;String&gt; aList ){
        for(String s: aList){
            System.out.println(s);
            s = s + &quot;ss&quot;;
        }
    }

字符串是不可变的。所以当你改变 s 时,你创建了一个新的对象,它与 ArrayList 中的那个不同。

因此,你需要遍历数组,并使用 set 方法将旧值替换为新值。

for (int i = 0; i &lt; alist.size(); i++) {
     String s = aList.get(i) + &quot;ss&quot;;
     aList.set(i, s);
}

要简单地追加更改,请执行以下操作:

int len = alist.size();
for (int i = 0; i &lt; len; i++) {
     String s = aList.get(i) + &quot;ss&quot;;
     aList.add(s);
}

打印结果:

> aa bb cc aass bbss ccss


<details>
<summary>英文:</summary>

public void modifyList(ArrayList<String> aList ){
for(String s: aList){
System.out.println(s);
s = s + "ss";
}
}


Strings are immutable.  So when you change `s` you are creating a new object that is different than the one in the ArrayList.

So you need to iterate over the array and replace the old value with the new using the `set` method.

for (int i = 0; i < alist.size(); i++) {
String s = aList.get(i) + "ss";
aList.set(i, s);
}

To simply append the changes do the following:

int len = alist.size();
for (int i = 0; i < len; i++) {
String s = aList.get(i) + "ss";
aList.add(s);
}

Prints

&gt; aa bb cc aass bbss ccss



</details>



# 答案2
**得分**: 1

`s = s + "ss"`只会更新局部变量`s`,不会更新列表。

如果你想要更新列表中的元素,可以使用[`ListIterator`][1]和[`set()`][2]方法:

```java
public static void modifyList(List<String> aList) {
	for (ListIterator<String> iter = aList.listIterator(); iter.hasNext(); ) {
		String s = iter.next();
		s = s + "ss";
		iter.set(s); // 用新值替换列表中的元素
	}
}

在Java 8及以上版本中,你可以使用lambda表达式replaceAll()方法:

public static void modifyList(List<String> aList) {
	aList.replaceAll(s -> s + "ss");
}

无论列表是否很好地处理随机访问,例如列表是LinkedList,这两种方法都能表现良好。

测试

public static void main(String[] args) {
	List<String> aList = new ArrayList<>(Arrays.asList("aa", "bb", "cc"));
	modifyList(aList);
	System.out.println(aList);
}

输出

[aass, bbss, ccss]
英文:

s = s + &quot;ss&quot; only updates the local variable s, it doesn't update the list.

If you want to update elements in a list, use a ListIterator and the set() method:

public static void modifyList(List&lt;String&gt; aList) {
	for (ListIterator&lt;String&gt; iter = aList.listIterator(); iter.hasNext(); ) {
		String s = iter.next();
		s = s + &quot;ss&quot;;
		iter.set(s); // replace element in the list with new value
	}
}

In Java 8+, you can use a lambda expression with the replaceAll() method:

public static void modifyList(List&lt;String&gt; aList) {
	aList.replaceAll(s -&gt; s + &quot;ss&quot;);
}

Both will perform well even if the list doesn't handle random access well, e.g. if the list is a LinkedList.

Test

public static void main(String[] args) {
	List&lt;String&gt; aList = new ArrayList&lt;&gt;(Arrays.asList(&quot;aa&quot;, &quot;bb&quot;, &quot;cc&quot;));
	modifyList(aList);
	System.out.println(aList);
}

Output

[aass, bbss, ccss]

答案3

得分: 1

问题在于变量s未被使用,且仅在for循环的作用域内可见:

for (String s: aList) {
    System.out.println(s);
    s = s + "ss";           // 变量's'未被使用
}

你可以使用List::set来替换当前值:

for (int i=0; i<aList.size(); i++) {
    String s = aList.get(i);
    System.out.println(s);
    aList.set(i, s + "ss");
}

... 或者利用 [tag:java-stream] 在 [tag:java-8] 中的优势,将列表映射为新列表:

List<String> newList = aList.stream()
                            .map(s -> s + "ss")
                            .collect(Collectors.toList());
英文:

Here is the problem, the variable s is unused and visible only in the scope of the for-loop:

for (String s: aList) {
    System.out.println(s);
    s = s + &quot;ss&quot;;           // the variable &#39;s&#39; is unused
}

Either use List::set to replace the current value:

for (int i=0; i&lt;aList.size(); i++) {
	String s = aList.get(i);
	System.out.println(s);
	aList.set(i, s + &quot;ss&quot;);
}

... or use the advantage of [tag:java-stream] as of [tag:java-8] and map the list to a new one:

List&lt;String&gt; newList = aList.stream()
                            .map(s -&gt; s + &quot;ss&quot;)
                            .collect(Collectors.toList());

答案4

得分: 0

为了解决这个问题,你需要按以下方式更新每个元素:

public void modifyList(ArrayList<String> aList){
        for(int i = 0; i < aList.size(); i++){
            String s = aList.get(i);
            aList.set(i, s + "ss");
        }
}
英文:

In order to solve this, you need to update each element as follows:

public void modifyList(ArrayList&lt;String&gt; aList){
        for(int i = 0; i &lt; aList.size(); i++){
            String s = aList.get(i);
            aList.set(i, s+&quot;ss&quot;);
        }
}

huangapple
  • 本文由 发表于 2020年4月4日 05:32:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/61020716.html
匿名

发表评论

匿名网友

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

确定