0

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!

Sawyer
  • 125
  • 3
  • TL;DR: java is pass-by-value but the value may not be what you expect it to be. – Federico klez Culloca Jun 14 '22 at 20:11
  • Thank you this is interesting. I am following exercises in a textbook and was under the impression non-primitive data types are passed by reference and not value, so this would work. :Shrug: – Sawyer Jun 14 '22 at 20:12

0 Answers0