问题
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