您的位置:首页 > 其它

两种方法删除ArrayList里重复元素

2014-09-28 14:37 337 查看
这里有两种方法帮你删除在一个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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: