gpt4 book ai didi

Java ArrayList.remove()

转载 作者:太空宇宙 更新时间:2023-11-04 09:20:36 25 4
gpt4 key购买 nike

我想从 t1 中删除单词“a”目的。为什么t2对象也受到影响?

代码:

package newproject;

import java.util.ArrayList;
import java.util.Arrays;

public class NewProject {

public static void main(String[] args) {
String str[] = {"a", "b", "c"};
ArrayList<String> words = new ArrayList<>();
words.addAll(Arrays.asList(str));

Test t1 = new Test(words);
Test t2 = new Test(words);

System.out.println("Result Before ");
System.out.println("T1 " + t1.getWords());
System.out.println("T2 " + t2.getWords());

// Only T1 remove words, not T2
t1.removeWords("a");

System.out.println("Result After ");
System.out.println("T1 " + t1.getWords());
System.out.println("T2 " + t2.getWords());
}

}

class Test {
private ArrayList<String> words;

Test(ArrayList<String> words){
setWords(words);
}

void setWords(ArrayList<String> words){
this.words = words;
}

ArrayList <String> getWords() {
return this.words;
}

void removeWords(String word) {
this.words.remove(word);
}
}

最佳答案

因为 t1 和 t2 共享相同的 ArrayList 。而不是传递 ArrayList在构造函数中,您希望构造函数说 this.words = new ArrayList<String>();确保 Test 的每个实例有自己的 Collection 。

关于Java ArrayList.remove(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58370314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com