Vincent Jia 博客

          to be a better man, to be a bad man.

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            29 隨筆 :: 3 文章 :: 0 評論 :: 0 Trackbacks
          LinkedHashSet是JDK 1.4中引入的新的集合類(LinkedHashMap也是同期引入)。 LinkedHashSet,顧名思義,就是在Hash的實現(xiàn)上添加了Linked的支持。對于LinkedHashSet,在每個節(jié)點上通過一個鏈表串聯(lián)起來,這樣,就可以保證確定的順序。對于希望有常量復(fù)雜度的高效存取性能要求、同時又要求排序的情況下,可以直接使用LinkedHashSet。

          它實現(xiàn)了Set接口。存入Set的每個元素必須是唯一的,因為Set不保存重復(fù)元素。但是Set接口不保證維護元素的次序(那里面的元素每次順序如何確定?TODO)。Set與Collection有完全一樣的接口Iterable,同時Set繼承了Collection。

          LinkedHashSet具有HashSet的查詢速度,且內(nèi)部使用鏈表維護元素的順序(插入的順序),于是在使用迭代器便利Set時,結(jié)果會按元素插入的次序顯示。

          需求如: 含多個(有重復(fù))元素ArrayList,去除重復(fù)。

          1, 可以使用如下略顯冗余的代碼:
           1 public static List removeDuplicateWithOrder(List list) {
           2         Set set = new HashSet();
           3         List newList = new ArrayList();
           4         for (Iterator iter = list.iterator(); iter.hasNext();) {
           5             Object element = iter.next();
           6             if (set.add(element))
           7                 newList.add(element);
           8         }
           9         return newList;
          10     }
          此方法有濫用set之嫌。

          2, 我們也可以使用本文章中提及的LinkedHashSet:
          return new ArrayList<T>(new LinkedHashSet<T>(list));
          此方法,既利用set去除了重復(fù),又使用linked保持住了原順序。

          3, 貌似apache commons lang中有專門去重復(fù)的集合工具。

          這兒的鏈表操作是常量級的,這也是LinkedHashSet/LinkedHashMap比TreeSet/TreeMap性能更高的原因。當(dāng)然,LinkedHashSet不是thread-safe的,在多線程環(huán)境下,需要進行同步包裝:
          Collections.synchronizedCollection(Collection);
          or:
          Collections.synchronizedSet(Set);
          在使用LinkedHashSet的iterator()方法遍歷元素時,如果其他線程有讀取操作,也要進行同步,否則,就會拋出同其它fail-fast一樣的由于刪除或增加操作而引起的CurrentModificationException。


          如上兩種方法的效率比較,設(shè)為TODO,
          1, 利用set.add(element)方法,本質(zhì)是利用其contains()方法判斷,而contains()的本質(zhì)就是遍歷。
          JDK doc中寫道:
          More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false. In combination with the restriction on constructors, this ensures that sets never contain duplicate elements.
          2, 測試數(shù)據(jù),可以使用數(shù)據(jù)量:1W,5W,10W,100W。

          posted on 2012-07-06 11:54 iLinux 閱讀(6227) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
          博客園   IT新聞   Chat2DB   C++博客   博問  
           
          主站蜘蛛池模板: 清水河县| 临沂市| 南昌市| 新竹县| 绥化市| 文水县| 临朐县| 囊谦县| 乌鲁木齐县| 离岛区| 巩留县| 古丈县| 祁东县| 南部县| 金门县| 喜德县| 东阿县| 如皋市| 清水县| 衡东县| 方山县| 齐河县| 西峡县| 米脂县| 广丰县| 乐东| 六盘水市| 舟山市| 阳谷县| 瓮安县| 容城县| 兰考县| 衡阳市| 土默特右旗| 温州市| 山东省| 武汉市| 江门市| 增城市| 石台县| 城步|