标签:style os java for ar sp new size on
Java中两种删除List中相同element的方法,一种维护List原先的元素顺序,另一种不维护List原先的元素顺序。
package stage3; import java.util.Iterator; public class RemoveTheElement { public static <E> void removeDuplicateWithoutOrder(java.util.List<E> list) { java.util.Set<E> set = new java.util.HashSet<E>(list); list.clear(); list.addAll(set); } public static <E> void removeDuplicateWithOrder(java.util.List<E> list) { java.util.Set<E> set = new java.util.HashSet<E>(); java.util.List<E> newList = new java.util.Vector<E>(); Iterator<E> iter = list.iterator(); while (iter.hasNext()) { E element = iter.next(); if (set.add(element)) { newList.add(element); } } list.clear(); list.addAll(newList); } public static void main(String[] args) { java.util.ArrayList<String> list1 = new java.util.ArrayList<>(); String str = "the apple and the banana"; System.out.println("source:" + str); list1.addAll(java.util.Arrays.asList(str.split(" "))); RemoveTheElement.removeDuplicateWithoutOrder(list1); System.out.print("target:"); for (String s : list1) { System.out.print(s + " "); } System.out.println(); java.util.ArrayList<Integer> list2 = new java.util.ArrayList<>(); Integer[] num = { 1, 2, 3, 4, 3, 5, 5, 2, 1 }; list2.addAll(java.util.Arrays.asList(num)); RemoveTheElement.removeDuplicateWithOrder(list2); for (int i : list2) { System.out.print(i + ","); } } }
输出比较:
第一种方法
source: the apple and the banana
target: the banana apple and
第二种方法
source: 1, 2, 3, 4, 3, 5, 5, 2, 1
target: 1,2,3,4,5,
标签:style os java for ar sp new size on
原文地址:http://my.oschina.net/keyven/blog/306660