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?
stringAList?