Wednesday, July 19, 2017

TreeSet / ConcurrentSortedList cannot be removed once the value changes

// Check this out.

class KK implements Comparable<KK> {
    public int value;
    public KK(int value) {
        this.value = value;    }

    @Override public int compareTo(KK o) {
        return Integer.compare(value, o.value);    
    }
}

@Testvoid test_treeset() {
    SortedSet<KK> set = new TreeSet<>();    
    KK a = new KK(5);    
    KK b = new KK(10);
    set.add(a);    set.add(b);
    set.forEach(item -> System.out.println(item.value));
    // change b to less than a -> this will not remove the value after b value changes.    
    // because it guranteed log n, so it will not find it.    
    b.value = 4;

    set.remove(b);
    System.out.println("After remove -> it will not remove value");    
    set.forEach(item -> System.out.println(item.value));}

No comments: