为什么这段代码会抛出异常

RAQ*_*RAQ -1 java classcastexception

    HashMap h = new HashMap();
    Collection c = h.values();
    Object[] a = c.toArray();
    LinkedList<Object[]> l = new LinkedList<Object[]>();
    l.addFirst(a);
    TreeSet<Object[]> t = new TreeSet<Object[]>(l); //throws ClassCastException exception
Run Code Online (Sandbox Code Playgroud)

由于我没有违反任何合同,这种例外很奇怪.

小智 6

如果传递了一个集合,其元素并不都实现Comparable,则TreeSet构造函数抛出ClassCastException.Object []没有实现Comparable.

有关更多详细信息,请参阅构造函数参考.

ClassCastException - 如果c中的元素不是Comparable,或者不能相互比较 NullPointerException - 如果指定的collection是null