为什么在jdk 1.6中TreeSet可以用作TreeMap的键? [英] Why TreeSet can be used as a key for TreeMap in jdk 1.6?

查看:146
本文介绍了为什么在jdk 1.6中TreeSet可以用作TreeMap的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这样做:

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");
    }
}

在Java 6中工作?我的意思是,通过在没有适当的Comparator的情况下将TreeSet作为TreeMap的键进行规范应会导致ClassCastException,但在Java 6下运行时则不会这样。是错误还是Java 7中进行了一些规范更改使其正常工作(即

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)?

推荐答案

Java 7中也允许这样做,而不仅仅是Java 6。

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

如果键的类型不是实现的类型,则 put 方法将引发 ClassCastException 可比较。可以将类设计为在构造函数中引发异常,但这不是因为

(a)泛型参数类型受到类型擦除,因此实际的 TreeMap 将所有内容视为普通对象,并且无法在构造函数中应用任何检查;

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)这种方式允许您将任何对象用作一个键,只要它是实现 Comparable 的子类,即使您最初没有声明 TreeMap 以采用可比较的密钥类型。

(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.

这篇关于为什么在jdk 1.6中TreeSet可以用作TreeMap的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆