<pre code_snippet_id="1582784" snippet_file_name="blog_20160219_1_9860537" name="code" class="plain">
Java 中Collection實現類ArrayList如何去除重複項。以下列出了幾種方法,以不同的方面去考慮。
(1)通過循環剔除重複項:使用雙向的for循環,依次取出集合中元素進行比較。【基本類型。自定義類型自定義比較方法】
public static void removeDuplicate(List list) {
for ( int i = 0 ; i < list.size() - 1 ; i ++ ) { //從左向右循環
for ( int j = list.size() - 1 ; j > i; j -- ) { //從右往左內循環
if (list.get(j).equals(list.get(i))) {
list.remove(j); //相等則移除
}
}
}
System.out.println(list);
}
(2)通過HashSet來過濾重複元素。【注意原始集合中元素順序已經被打亂】
注意使用hash表時候,要重寫集合元素中對象的hashCode和equals方法。
public static void removeDuplicate(List list) {
HashSet h = new HashSet(list); //元素無序
list.clear();
list.addAll(h);
System.out.println(list);
}
其中通過HashSet的帶List參數進行構造哈希表。將原始List中所有元素複製到HashSet中。然後再將原始List所有內容刪除,最後將過濾掉的無重的元素添加到List中。
其中HashSet帶List的構造函數源代碼如下:
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16)); //底層通過hashmap來操作hashset.
addAll(c);
}
(3)最後一種,是考慮到原始集合中元素順序。也是通過hashSet實現的。但是通過新創建一個List集合將每個通過HashSet過濾的元素依次存入新集合中。
所以就是在原始集合上去除了重複元素,但是元素的相對位置是 不變的。
public static void removeDuplicateWithOrder(List list) {
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = list.iterator(); iter.hasNext();) {
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
list.clear();
list.addAll(newList);
System.out.println( " remove duplicate " + list);
}
public boolean add(E e) {
return map.put(e, PRESENT)==null; //底層通過HashMap的put方法添加元素。
}
其中,判斷是否重複,是通過HashSet的add方法的返回值來判斷,添加成功,則代表元素之前不存在,反之,則代表添加的元素是重複元素。
**總之,合適環境使用適當的方式去實現。