两种方法删除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);
}

此条目发表在java/j2ee分类目录,贴了标签。将固定链接加入收藏夹。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据