Created
July 21, 2024 15:40
-
-
Save dk2k/b69e54a38f58633879f579c85715bb66 to your computer and use it in GitHub Desktop.
Inconsistent comparison
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package changeme; | |
import java.util.Comparator; | |
import java.util.TreeSet; | |
public class SortDemo { | |
public static void main(String[] args) { | |
Comparator<Element> comparator = new Comparator<Element>() { | |
@Override | |
public int compare(Element o1, Element o2) { | |
if (o1.getIntField() < o2.getIntField()) { | |
return -1; | |
} else if (o1.getIntField() > o2.getIntField()) { | |
return 1; | |
} | |
// Inconsistent comparison: doesn't return 0 for equal objects | |
return 1; | |
} | |
}; | |
TreeSet<Element> set = new TreeSet<>(comparator); | |
Element element1 = new Element(1); | |
Element element2 = new Element(1); | |
Element element3 = new Element(-1); | |
Element element4 = new Element(-1); | |
Element element5 = new Element(0); | |
Element element6 = new Element(2); | |
Element element7 = new Element(-2); | |
set.add(element1); | |
set.add(element2); | |
set.add(element3); | |
set.add(element4); | |
set.add(element5); | |
set.add(element6); | |
set.add(element7); | |
System.out.println(set.higher(element5)); // expect 1, got 1 | |
System.out.println(set.lower(element5)); // expect -1, got 0 | |
System.out.println(set.tailSet(element1)); // expect 1 2, got 2 | |
} | |
static class Element { | |
private Integer intField; | |
public Element(Integer intField) { | |
this.intField = intField; | |
} | |
public Integer getIntField() { | |
return intField; | |
} | |
public void setIntField(Integer intField) { | |
this.intField = intField; | |
} | |
@Override | |
public String toString() { | |
return "Element{" + | |
"intField=" + intField + | |
'}'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment