如何删除ArrayList里重复元素?
如何删除ArrayList里重复元素?
这里有两种方法帮你删除在一个ArrayList里重复的elements。下面的程序片段里,removeDuplicate方法不维护顺序 (Order),而removeDuplicateWithOrder方法会保持顺序 (Order),但会有些性能上的牺牲。
The removeDuplicate Method:
/** List order not maintained **/
public static void removeDuplicate(ArrayList arlList)
{
HashSet h = new HashSet(arlList);
arlList.clear();
arlList.addAll(h);
}
The removeDuplicateWithOrder Method:
/** List order maintained **/
public static void removeDuplicateWithOrder(ArrayList arlList)
{
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = arlList.iterator(); iter.hasNext(); ) {
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
arlList.clear();
arlList.addAll(newList);
}