作者: sealyu   日期:2009-1-8
在项目中碰到一个bug,抛出ClassCastException异常,找了半天,终于定位问题所在。
在TreeSet的javadoc里写到:
/**
     * Constructs a new, empty set, sorted according to the elements' natural
     * order.  All elements inserted into the set must implement the
     * <tt>Comparable</tt> interface.  Furthermore, all such elements must be
     * <i>mutually comparable</i>: <tt>e1.compareTo(e2)</tt> must not throw a
     * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
     * <tt>e2</tt> in the set.  If the user attempts to add an element to the
     * set that violates this constraint (for example, the user attempts to
     * add a string element to a set whose elements are integers), the
     * <tt>add(Object)</tt> call will throw a <tt>ClassCastException</tt>.
     *
     * @see Comparable
     */
    public TreeSet() {
    this(new TreeMap<E,Object>());
    }
也就是说,在使用零参的构造函数时,你所要插入set的elements必须都声明Comparable接口。
如果没有声明该接口,当你对里面的元素进行排序或者比较操作(所有调用e1.compareTo(e2)的操作),都会抛出一个ClassCastException。同时任何试图插入没有声明该接口的元素也会抛出此异常。
谨记!