如果用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); }
1 方法二:通过HashSet剔除 2 // 删除ArrayList中重复元素 3 public static void removeDuplicate(List list) { 4 HashSet h = new HashSet(list); 5 list.clear(); 6 list.addAll(h); 7 System.out.println(list); 8 }
1 方法三: 删除ArrayList中重复元素,保持顺序 2 // 删除ArrayList中重复元素,保持顺序 3 public static void removeDuplicateWithOrder(List list) { 4 Set set = new HashSet(); 5 List newList = new ArrayList(); 6 for (Iterator iter = list.iterator(); iter.hasNext();) { 7 Object element = iter.next(); 8 if (set.add(element)) 9 newList.add(element); 10 } 11 list.clear(); 12 list.addAll(newList); 13 System.out.println( " remove duplicate " + list); 14 }
如果用HashSet的话,如果是对象,则要将对象实现equals和hashCode方法
春风如贵客,一到便繁华