Woogear
Woogear

Reputation: 67

Sorting ArrayList with sorted Array in Java Ends Up with Different Results

I want to sort an array by sizes of its int numbers(from small to big) and I want to do another arrayList with the same sequence of the array.

In this case, my array is "workHour" and the arrayList is "sortedList" from startHour.

I followed someone's advice from here.

And I wrote my code like below.

int[] workHour = new int[]{4,2,6,2,5,4, 4, 3, 4,11, 2};
String[] startHour = new String[] {"1","3", "0", "5","3", "5", "6", "8", "8", "2","12"};

final List<String> stringListCopy = Arrays.asList(startHour);
ArrayList<String> sortedList = new ArrayList<>(stringListCopy);
Collections.sort(sortedList, (o1, o2) -> workHour[stringListCopy.indexOf(o1)] - workHour[stringListCopy.indexOf(o2)]);

Arrays.sort(workHour);
System.out.println(sortedList);

The reason why I put String instead of Integer into arrayList is because I got the same result, so I switched into String to test my code.

And I got a result like this:

[3, 5, 3, 5, 12, 8, 8, 1, 6, 0, 2]

Not like I expected:

[3, 5, 12, 8, 1, 5, 6, 8, 3, 0, 2]

However when I change the array like this:

String[] startHour = new String[] {"c1","a1","e","a2","d","c2","c3","b","c4","f","a3"};

It gives me what I expected:

[a1, a2, a3, b, c1, c2, c3, c4, d, e, f]

I simply changed String array with something that I can see the result more easily and I just don't know what makes this difference and why it behaves like this.

I think I need to know about the Comparator class.. Can anyone explain this?

Upvotes: 0

Views: 199

Answers (1)

mangusta
mangusta

Reputation: 3544

It works for this case: {"c1","a1","e","a2","d","c2","c3","b","c4","f","a3"} because all elements are unique.
indexOf method returns the index of the first occurence of a given element and since your original array i.e. {"1","3", "0", "5","3", "5", "6", "8", "8", "2","12"} contains duplicates, indexOf is going to return same value for elements "3", "5" and "8" (returns 1 for both"3", 3 for both "5", 7 for both "8")

I don't think you can apply Comparator here since it uses the values of compared elements and your problem requires inspection of indices of compared elements without checking their actual values (well, unless you guarantee that the elements are unique)

Or you may create a list of class Pair with string field having value of strings that your original list consists of, and int field having value of index of corresponding string. In that case you may use comparator to sort the list of pairs and after that you get your sorted list of strings by iterating through the sorted list of pairs

Upvotes: 1

Related Questions