Two Methods to Remove Duplicates in an ArrayList
Here are two methods that allow you to remove duplicates in an ArrayList. removeDuplicate does not maintain the order where as removeDuplicateWithOrder maintains the order with some performance overhead.
1.The removeDuplicate Method: /** List order not maintained **/ public static void removeDuplicate(ArrayList arlList)
{
HashSet h = new HashSet(arlList);
arlList.clear();
arlList.addAll(h);
}
2.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);
}
本文介绍两种去除ArrayList中重复元素的方法:一种不保持原有顺序,利用HashSet的特性快速去除重复;另一种保持顺序,通过迭代检查并添加未重复元素到新列表。
2529

被折叠的 条评论
为什么被折叠?



