I want to remove word "a" from t1
object. Why t2
object also got affected?
Code:
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);
}
}