Sealyu

--- 博客已迁移至: http://www.sealyu.com/blog

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  618 随笔 :: 87 文章 :: 225 评论 :: 0 Trackbacks
作者: 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。同时任何试图插入没有声明该接口的元素也会抛出此异常。
谨记!

posted on 2009-01-08 09:40 seal 阅读(1478) 评论(3)  编辑  收藏 所属分类: Java基础

评论

# re: TreeSet()零参构造函数引起的问题 2009-01-08 10:12 徐尧
恩,挺好  回复  更多评论
  

# re: TreeSet()零参构造函数引起的问题 2009-01-08 12:05 逝水fox
TreeSet和TreeMap都需要一个排序算法来维护顺序 而这个排序算法就必须要由元素自身实现Comparable或者外置的排序算法Comparator来实现了
不过用的时候 编译器是没有什么提示的 这里确实不是很好咯  回复  更多评论
  

# re: TreeSet()零参构造函数引起的问题 2009-01-11 23:27 爱吃鱼头
@逝水fox
学习了,谢谢哦  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: