I recently upgraded our jdk application from Java 6 to Java 8, but still kept the source language level as Java 6. After changing one of our unit tests, it crashed. I noticed that Collections.sort for LinkedList works differently in Java 8 and Java 6. Even when I am the original level of java 8 with JDk 1.8, I have the same behavior. To recreate the problem: Listing Definition below:
public enum Weight { A(1), B(0), C(0), D(0), E(2); public int getWeight() { return weight; } private int weight; Weight(int weight) { this.weight = weight; } @Override public String toString() { return name() + '(' + weight + ')'; } }
and main class as below:
public class Main { public static void main(String[] args) { List<Weight> weightList = new LinkedList<Weight>(); weightList.add(Weight.A); weightList.add(Weight.B); weightList.add(Weight.C); weightList.add(Weight.D); weightList.add(Weight.E); Collections.sort(weightList, new Comparator<Weight>() { @Override public int compare(Weight o1, Weight o2) { return o1.getWeight() > o2.getWeight()? 1:0; } }); System.out.print(weightList); } }
Output for running code under Java 6: "C: \ Program Files \ Java \ jdk1.6.0_45 \ bin \ java"
[B (0), C (0), D (0), A (1), E (2)]
and output for running code under java 8:
"C: \ Program Files (x86) \ Java \ jdk1.8.0_161 \ bin \ java"
[A (1), B (0), C (0), D (0), E (2)]
I changed the type from LinkedList to ArrayList , and I get the same result, but if I change the comparator as shown below, then Java 8 will sort the array:
Collections.sort(weightList, new Comparator<Weight>() { @Override public int compare(Weight o1, Weight o2) { return o1.getWeight() > o2.getWeight()? 1:-1; } });
As you can see, it seems that java 8 is not sorting the code correctly. Is there a bug in Java or am I missing something as usual?