TreeSet giving incorrect output - Java8

前端 未结 4 1450
太阳男子
太阳男子 2021-01-31 14:56

While working with a tree set, I found very peculiar behavior.

As per my understanding following program should print two identical lines:

public class T         


        
4条回答
  •  半阙折子戏
    2021-01-31 15:15

    To add some information about why the remove of TreeSet actually removes case-insensively in your example (and provided that you follow the if (size() > c.size()) path as explained in the answer by @Shadov) :

    This is the removemethod in TreeSet :

    public boolean remove(Object o) {
            return m.remove(o)==PRESENT;
        }
    

    it calls remove from its internal TreeMap :

    public V remove(Object key) {
        Entry p = getEntry(key);
        if (p == null)
            return null;
    
        V oldValue = p.value;
        deleteEntry(p);
        return oldValue;
    }
    

    which calls getEntry

     final Entry getEntry(Object key) {
            // Offload comparator-based version for sake of performance
            if (comparator != null)
                return getEntryUsingComparator(key);
            if (key == null)
                throw new NullPointerException();
            @SuppressWarnings("unchecked")
                Comparable k = (Comparable) key;
            Entry p = root;
            while (p != null) {
                int cmp = k.compareTo(p.key);
                if (cmp < 0)
                    p = p.left;
                else if (cmp > 0)
                    p = p.right;
                else
                    return p;
            }
            return null;
        }
    

    If there is a Comparator (as in your example), the entry is searched based on this Comparator (this is done by getEntryUsingComparator), that's why it is actually found (then removed) , despite the case difference.

提交回复
热议问题