0

I can't get this method to modify an ArrayList then return the modified ArrayList.

public static ArrayList<Integer> sortAndRemoveDuplicates(ArrayList<Integer> list) {
        list = new ArrayList<Integer>(new HashSet<Integer>(list));
        Collections.sort(list);
        //System.out.println(list);
        return list;
}

When I uncomment the System call I can see that the ArrayList is being modified and I know that my method works but when I run the method through main the ArrayList remains unaffected. Why is this? What am I doing wrong?

Why isn't this modified version working?

public static ArrayList<Integer> sortAndRemoveDuplicates(ArrayList<Integer> list) {
    ArrayList<Integer> newList = new ArrayList<Integer>(new HashSet<Integer>(list));
    Collections.sort(newList);
    System.out.println(newList);
    return newList;
}
aeipownu
  • 107
  • 3
  • 17

3 Answers3

1

You are creating new ArrayList from passed list so You need to catch result back

List<Integer> result = sortAndRemoveDuplicates(inputList)
jmj
  • 237,923
  • 42
  • 401
  • 438
1

Java passes references by value. You are re-assigning the input reference that points to the initial list to another object. The original list will remain pointing to the original ArrayList object.

You need to assign this newly created list back to the original reference:

originalList = sortAndRemoveDuplicates(originalList);

EDIT: Alternatively, since you are not returning the value to the caller method (main), you can make your method's return type void and modify your input list as follows:

public static void sortAndRemoveDuplicates(List<Integer> list) {
    List<Integer> newList = new ArrayList<Integer>(new HashSet<Integer>(list));
    Collections.sort(newList);
    System.out.println(newList);
    list.clear();
    for(Integer integer : newList) {
        list.add(integer);
    }
}

Note: It is best practice to program to interfaces instead of concrete implementations, i.e. let your newList be declared of type List instead of ArrayList.

Community
  • 1
  • 1
M A
  • 71,713
  • 13
  • 134
  • 174
0

I think your expectations are not met because everything in Java is pass by value so the modifications to the list are made to a copy, not your original list. Unless you return and capture the modified copy, you will not see the changes in the calling code on return from the method.

JamesB
  • 7,774
  • 2
  • 22
  • 21