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 閱讀(1501) 評論(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
          學習了,謝謝哦  回復  更多評論
            

          主站蜘蛛池模板: 南涧| 陈巴尔虎旗| 始兴县| 德惠市| 灌云县| 西吉县| 稻城县| 贵溪市| 佳木斯市| 东城区| 尖扎县| 黎川县| 宽甸| 涟水县| 贵德县| 和田县| 屏南县| 巴东县| 隆子县| 大埔区| 安丘市| 大余县| 新邵县| 宜丰县| 乐业县| 兴宁市| 灌阳县| 台州市| 永城市| 明溪县| 光泽县| 伊宁市| 新闻| 安塞县| 沙雅县| 江都市| 特克斯县| 英山县| 肇源县| 板桥市| 长沙县|