去除List中重複元素
阿新 • • 發佈:2019-01-30
轉載自:http://blog.csdn.net/mwq384807683/article/details/8088706
用Set ,倘若list裡邊的元素不是基本資料型別而是物件,那麼請覆寫Object的boolean equals(Object obj) 和int hashCode()方法. return new ArrayList(new HashSet(list)); 方法一:迴圈元素刪除 // 刪除ArrayList中重複元素 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); } 方法二:通過HashSet剔除 // 刪除ArrayList中重複元素 public static void removeDuplicate(List list) { HashSet h = new HashSet(list); list.clear(); list.addAll(h); System.out.println(list); } 方法三: 刪除ArrayList中重複元素,保持順序 // 刪除ArrayList中重複元素,保持順序 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); } 如果用HashSet的話,如果是物件,則要將物件實現equals和hashCode方法