1

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?

2
  • 4
    In any case: Do NOT sort a list to obtain the "biggest value". That's what Collections.max(collection) is for! Commented Jul 27, 2014 at 14:11
  • @Marco13 thank you for the information, i am now one step away from stop being a nub:) anyway it's just an example Commented Jul 27, 2014 at 14:18

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.