为什么 java 允许 TreeMap 键和 TreeSet 值不可比较? [英] Why java allows TreeMap keys and TreeSet values to be non comparable?

查看:37
本文介绍了为什么 java 允许 TreeMap 键和 TreeSet 值不可比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java TreeMap 实现的头文件(1.8_071):

Here's header of java TreeMap implementation(1.8_071):

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable

为什么没有限制,像这样:

Why there's no restriction, like this:

 public class TreeMap<K extends Comparable<?>,V>
        extends AbstractMap<K,V>
        implements NavigableMap<K,V>, Cloneable, java.io.Serializable

推荐答案

因为,正如文档所说,您可以使用不是 Comparable 的键并提供 Comparator 对象:

Because, as the doc says, you can use a key that is not a Comparable and provide a Comparator object:

TreeMap(Comparator<? super K> comparator)
Constructs a new, empty tree map, ordered according to the given comparator.

(https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html)

这篇关于为什么 java 允许 TreeMap 键和 TreeSet 值不可比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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