Search code examples
javaclasscastexception

Why does this code throws exception


    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

Since I'm not violating any contracts, this exception is weird.


Solution

  • The TreeSet constructor throws a ClassCastException if a collection is passed whose elements do not all implement Comparable. Object[] does not implement Comparable.

    Refer to the constructor reference for more details.

    ClassCastException - if the elements in c are not Comparable, or are not mutually comparable NullPointerException - if the specified collection is null