0

I want to sort a list of numbers without change the original list. So this is what I did:

public double median(){
    //first,sort the list
    LinkedList<Double>sorted = entries;
    Collections.sort(sorted); ...

entries is another LinkedList that I would like to have it unsorted. I created a new LinkedList named sorted for not changing the original entries list. The sorted list is only used for this double function. However everytime when I call the function it still sorts the entries list.

How can I sort it without changing the original list?

What I've done so far:

  1. LinkedListsorted = entries;

2.

LinkedList<Double>sorted = new LinkedList<Double>();
Collections.copy(sorted,entries);

3.

LinkedList<Double>sorted = new LinkedList<Double>();
for(int i=0;i<entries.size();i++){
sorted.add(entries.get(i));}

And none of them are working properly. They do the sort work, but they changed the entries list which I don't want to change.


Thanks everyone. The problem is now solved. I copy pasted them to another software and paste back and it now works properly. I still can't understand why though.

Nina Z
  • 19
  • 4
  • 3
    _I created a new LinkedList_ <-- No, you didn't. You created another reference to the same list. – Joe C Nov 04 '18 at 21:23
  • Do `LinkedList sorted = new LinkedList<>(entries);`. To understand the underlying cause of the behavior you see, take a look at https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – lakshayg Nov 04 '18 at 21:25

2 Answers2

2

You haven't created a new list, you have just assigned it to variable called sorted, if want to have a sorted copy then you would need to copy it to another list as follows.

LinkedList<Double> sorted = new LinkedList<Double>();
Collections.copy(sorted, entries);
Collections.sort(sorted);
Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
1
public static LinkedList<Double> sort(LinkedList<Double> list) {
    LinkedList<Double> res = new LinkedList<>(list);
    Collections.sort(res);
    return res;
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35