3

I have three ArrayLists:
One is used for storing user input in the order they were entered, located in the main class.
Second one is exactly the same as the first one, but it is passed into a method called remTrip to be copied and will return the result.
Third one is list1 in the code below, which is the one being processed.

public static ArrayList<String> remTrip( ArrayList<String> a){
    //code here
    ArrayList<String> list1 = a;
    Collections.sort(list1);
    //code to remove triplicates from the list and returns the result
}

I wanted to keep the first ArrayList<String> in the same order it was (i.e. {"dog", "cat" , "tiger", "cat", "cat"} ), but apparently the Collections.sort() sorts all of the ArrayLists.

How do I sort only one of the list and not the others?

Dr.jacky
  • 3,341
  • 6
  • 53
  • 91
Leonardo Vinsen
  • 89
  • 1
  • 12
  • 2
    Since you assigned `list1` to the same list as `a` (they are referring to the same object), why does this outcome surprise you? If you need to have two lists, one sorted and one not, what would seem like a logical approach? – KevinO Apr 20 '16 at 04:24
  • See also http://stackoverflow.com/q/40480/2891664 also http://stackoverflow.com/q/19843506/2891664. All your lists are actually the same list. – Radiodef Apr 20 '16 at 04:25
  • 1
    Except for primitive types, java variables are references to objects, not object values themselves. So when you assign `list1 = a` you are not copying a List, you are copying a, a reference to a list onto list1, another reference so that now list1 and a have the same reference, and point to the same List. If you want to copy the List in the assignment instead of the reference to the List, try `list1 = new ArrayList<>(a);` – Hank D Apr 20 '16 at 04:31

2 Answers2

6

The problem is not how Collections.sort() works. The problem is that instead of creating a copy of your list, you set the new list equal to your list. This means that they both point to the same object, sorting one will sort the other because they are the same thing. To solve this set list1 to a copy of a instead of setting them equal.

You should be able to do

ArrayList<String> list1 = new ArrayList<String>(a);
nhouser9
  • 6,730
  • 3
  • 21
  • 42
3

Three arralists you're talking about are not 3 different arraylists. They're just three different references to the same arraylist.

What you're doing essentially is -

List list01 = new ArrayList();
List list02 = list01;
List list03 = list01;

What you want is -

List list01 = new ArrayList();
List list02 = new ArrayList(list01);
List list03 = new ArrayList(list01);

But you should remember, this way will give you a copy of your List, not all it's elements. So, if you change one of the elements in your copied List, it will be changed in your original List too.

How to solve it - Hint copy constructor.

Raman Shrivastava
  • 2,923
  • 15
  • 26