Let's say I initialise my list like so:
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<String>();
a.add("one");
a.add("two");
a.add("three");
a.add("four");
modifyList(a);
}
where modifyList
simply changes every value to "one" like so:
private static void modifyList(ArrayList<String> a) {
for (int i = 0; i < a.size(); i++) {
a.set(i, "one");
}
}
If I print the list before and after I call this method, I expect the same original list to appear twice. But for some reason, the ArrayList that gets modified in modifyList
is the same as the ArrayList in main
.
If I try the same experiment with ints and Strings instead of Lists they do not get modified.
Can anyone explain why?