简体   繁体   中英

Why does TreeSet's add method behaves differently in different JREs?

I try to add objects of Employee class to a TreeSet. I don't implement Comparable or Comparator interface. But the add method code behaves differently in different systems. Why so? Code snippet below:-

import java.util.Set;
import java.util.TreeSet;

public class TreeSetTest {
public static void main(String[] args) {

    Set<Employee> set = new TreeSet<Employee>();
    set.add(new Employee());
//  set.add(new Employee());
//  set.add(new Employee());
 }
}

On the current system (Win 10), whether I write set.add() method once or thrice. It always throws ClassCastException at runtime. But talking of this question- Why does TreeSet throws ClassCastException The user there has written, that he doesn't get exception when he uses add method only once.

Also, in another system (Win 7), yesterday I had tried adding object 3 times, calling set method thrice, and there is no ClassCastException!! The size of set remains 1 only, so it appeared that multiple objects are just NOT getting added to set.

So what could be the reason for different-different kind of behavior of add method?

TreeSet.add() delegates to TreeMap.put() , which has differing behavior in Java 6 and Java 8.

Java 6 :

public V put(K key, V value) {
    Entry<K,V> t = root;
    if (t == null) {
        // TBD:
        // 5045147: (coll) Adding null to an empty TreeSet should
        // throw NullPointerException
        //
        // compare(key, key); // type check
        root = new Entry<K,V>(key, value, null);
        size = 1;
        modCount++;
        return null;
    }
    ...

Java 8 :

public V put(K key, V value) {
    Entry<K,V> t = root;
    if (t == null) {
        compare(key, key); // type (and possibly null) check

        root = new Entry<>(key, value, null);
        size = 1;
        modCount++;
        return null;
    }
    ...

As you can see, the earlier version had the compare() line commented out for some reason, but it was added back in the later version. Hence the exception you're seeing for the first element.

See here also: Why TreeSet can be used as a key for TreeMap in jdk 1.6?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM