Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
An example of pathological behaviour of TreeSet when ordering is inconsistent with equals
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