英文:
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<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(String s: aList){
            System.out.println(s);
            s = s + "ss";
        }
    }
}
Its printing
aa
bb
cc
aa
bb
cc
Expected output
aa
bb
cc
aass
bbss
ccss
答案1
得分: 1
public void modifyList(ArrayList<String> aList ){
        for(String s: aList){
            System.out.println(s);
            s = s + "ss";
        }
    }
字符串是不可变的。所以当你改变 s 时,你创建了一个新的对象,它与 ArrayList 中的那个不同。
因此,你需要遍历数组,并使用 set 方法将旧值替换为新值。
for (int i = 0; i < alist.size(); i++) {
     String s = aList.get(i) + "ss";
     aList.set(i, s);
}
要简单地追加更改,请执行以下操作:
int len = alist.size();
for (int i = 0; i < len; i++) {
     String s = aList.get(i) + "ss";
     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
> 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 + "ss" 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<String> aList) {
	for (ListIterator<String> iter = aList.listIterator(); iter.hasNext(); ) {
		String s = iter.next();
		s = s + "ss";
		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<String> aList) {
	aList.replaceAll(s -> s + "ss");
}
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<String> aList = new ArrayList<>(Arrays.asList("aa", "bb", "cc"));
	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 + "ss";           // the variable 's' is unused
}
Either use List::set to replace the current value:
for (int i=0; i<aList.size(); i++) {
	String s = aList.get(i);
	System.out.println(s);
	aList.set(i, s + "ss");
}
... or use the advantage of [tag:java-stream] as of [tag:java-8] and map the list to a new one:
List<String> newList = aList.stream()
                            .map(s -> s + "ss")
                            .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<String> aList){
        for(int i = 0; i < aList.size(); i++){
            String s = aList.get(i);
            aList.set(i, s+"ss");
        }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论