Potato Salad
Potato Salad

Reputation: 37

Collection.sort(arraylist) in a function sorting another arraylist

say, I made an arraylist in (public class class1(String args[]))

static List<Double> list1 = new ArrayList<Double>();

then I pass this arraylist to a function in (public static void main(String args[]))

biggestvalue(list1);

this is the function for example:

public static double biggestvalue(List<Double> list){
    Collections.sort(list);
    return list.get(list.size()-1);
}

I pass it into a function so that hopefully it will only sort list but not list1, but then list1 gets sorted as well, and I do not understand why that is. Therefore, please explain to me why that is, and what solutions to this error are out there?

Upvotes: 1

Views: 244

Answers (2)

August
August

Reputation: 12558

list1 gets sorted as well because you are passing a reference to that object. You want to duplicate the list before sorting it, so the original object doesn't get modified:

List<Double> dup = new ArrayList<>(list);
Collections.sort(dup);
return dup.get(dup.size() - 1);

Upvotes: 1

Keppil
Keppil

Reputation: 46239

You only pass a reference to the List when you pass it as an argument. Therefore, both list and list1 point to the same List.

A good rule of thumb is to not modify objects passed into a method, so I would make a copy inside the method:

public static double biggestvalue(List<Double> list){
    List<Double> temp = new ArrayList<>(list);
    Collections.sort(temp);
    return temp.get(temp.size()-1);
}

Upvotes: 3

Related Questions