For context, testList
is an object of class ArrayList<Integer>
and contains 20-pregenerated Integers of random value. Consider the following method in the main class:
public static void removeDuplicated(ArrayList<Integer> list) {
ArrayList<Integer> distinctElements = new ArrayList<>();
for (Integer integer : list) {
if (!distinctElements.contains(integer)) {
distinctElements.add(integer);
}
}
System.out.println(distinctElements.toString());
list = distinctElements; //Sending list to garbage collector
System.out.println(list.toString()); //Works as intended- list is printed w/o duplicates
}
Then, in the main
method:
...
removeDuplicated(testList);
System.out.println(testList.toString()); //Prints the original testList with(!) duplicates
...
Why does my reference reassignment in the top method line 8 not send testList
as it was originally generated to the garbage collector? Thanks for the help!