Last active
August 29, 2015 14:20
-
-
Save sorokod/ee5ea83288198814c650 to your computer and use it in GitHub Desktop.
An example of pathological behaviour of TreeSet when ordering is inconsistent with equals
This file contains 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
import java.util.Comparator; | |
import java.util.TreeSet; | |
// Blog post: http://david-soroko.blogspot.co.uk/2015/05/a-kink-in-api.html | |
public class TreeSetExample { | |
public static class Transaction { | |
private final String id; | |
private final int amount; | |
public Transaction(String id, int amount) { | |
this.id = id; | |
this.amount = amount; | |
} | |
public int getAmount() { | |
return amount; | |
} | |
@Override | |
public int hashCode() { | |
return id != null ? id.hashCode() : 0; | |
} | |
@Override | |
public boolean equals(Object o) { | |
if (this == o) return true; | |
if (o == null || !(o instanceof Transaction)) return false; | |
return id.equals(((Transaction) o).id); | |
} | |
} | |
public static class TransactionComparator implements Comparator<Transaction> { | |
@Override | |
public int compare(Transaction t1, Transaction t2) { | |
return t1.getAmount() - t2.getAmount(); | |
} | |
} | |
public static void main(String[] args) { | |
TreeSet<Transaction> set = new TreeSet<>(new TransactionComparator()); | |
Transaction t1 = new Transaction("T1", 100); | |
Transaction t2 = new Transaction("T2", 100); | |
System.out.printf("set did not already contain t1: %b\n", set.add(t1)); // set did not already contain t1: true | |
System.out.printf("set did not already contain t2: %b\n", set.add(t2)); // set did not already contain t2: false | |
System.out.printf("|set| = %d\n", set.size()); // |set| = 1 | |
System.out.printf("t1 is a member of set: %b\n", set.contains(t1)); // t1 is a member of set: true | |
System.out.printf("t2 is a member of set: %b\n", set.contains(t2)); // t2 is a member of set: true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment