Sealyu

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

            BlogJava :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            618 隨筆 :: 87 文章 :: 225 評(píng)論 :: 0 Trackbacks
          作者: sealyu   日期:2009-1-8
          在項(xiàng)目中碰到一個(gè)bug,拋出ClassCastException異常,找了半天,終于定位問(wèn)題所在。
          在TreeSet的javadoc里寫(xiě)到:
          /**
               * 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>());
              }

          也就是說(shuō),在使用零參的構(gòu)造函數(shù)時(shí),你所要插入set的elements必須都聲明Comparable接口。
          如果沒(méi)有聲明該接口,當(dāng)你對(duì)里面的元素進(jìn)行排序或者比較操作(所有調(diào)用e1.compareTo(e2)的操作),都會(huì)拋出一個(gè)ClassCastException。同時(shí)任何試圖插入沒(méi)有聲明該接口的元素也會(huì)拋出此異常。
          謹(jǐn)記!

          posted on 2009-01-08 09:40 seal 閱讀(1500) 評(píng)論(3)  編輯  收藏 所屬分類: Java基礎(chǔ)

          評(píng)論

          # re: TreeSet()零參構(gòu)造函數(shù)引起的問(wèn)題 2009-01-08 10:12 徐堯
          恩,挺好  回復(fù)  更多評(píng)論
            

          # re: TreeSet()零參構(gòu)造函數(shù)引起的問(wèn)題 2009-01-08 12:05 逝水fox
          TreeSet和TreeMap都需要一個(gè)排序算法來(lái)維護(hù)順序 而這個(gè)排序算法就必須要由元素自身實(shí)現(xiàn)Comparable或者外置的排序算法Comparator來(lái)實(shí)現(xiàn)了
          不過(guò)用的時(shí)候 編譯器是沒(méi)有什么提示的 這里確實(shí)不是很好咯  回復(fù)  更多評(píng)論
            

          # re: TreeSet()零參構(gòu)造函數(shù)引起的問(wèn)題 2009-01-11 23:27 愛(ài)吃魚(yú)頭
          @逝水fox
          學(xué)習(xí)了,謝謝哦  回復(fù)  更多評(píng)論
            

          主站蜘蛛池模板: 宿松县| 五常市| 饶阳县| 类乌齐县| 桃江县| 定陶县| 深泽县| 云阳县| 太湖县| 肃宁县| 祁门县| 龙南县| 新建县| 彝良县| 静海县| 太谷县| 石家庄市| 额尔古纳市| 绥芬河市| 金溪县| 绩溪县| 太谷县| 天全县| 同心县| 侯马市| 河池市| 宁海县| 贡觉县| 黄浦区| 偏关县| 紫云| 潼关县| 都昌县| 临泽县| 东台市| 大荔县| 镇安县| 乌兰县| 静安区| 盘山县| 平顺县|