Why TreeSet can be used as a key for TreeMap in jdk 1.6?

此生再无相见时 提交于 2019-12-13 18:42:58

问题


why does this:

import java.util.*;

public class my {
    public static void main(String[] a) {
        TreeMap<TreeSet<Integer>, String> map = new TreeMap<TreeSet<Integer>, String>();
        TreeSet<Integer> set = new TreeSet<Integer>();
        map.put(set, "lol");
    }
}

work in Java 6? I mean that by specification putting TreeSet as a key of TreeMap without proper Comparator should lead to ClassCastException but it doesn't when running under Java 6. Was it a bug or there were some specification changes in Java 7 that made it work correctly (i.e. throw ClassCastException)?


回答1:


This is allowed in Java 7 too, not just Java 6.

The put method will throw a ClassCastException if the key is not of a type that implements Comparable. The class could have been designed to throw the exception in the constructor, but it doesn't because
(a) generic parameter types are subjected to type erasure, so the actual TreeMap sees everything as a plain Object and can't apply any checks in the constructor;

(b) this way allows you to use any object as a key, as long as it is of a subclass that implements Comparable, even if you don't initially declare the TreeMap to take a comparable key type.



来源:https://stackoverflow.com/questions/33634083/why-treeset-can-be-used-as-a-key-for-treemap-in-jdk-1-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!