总结了两种删除ArrayList中重复元素的方法。
方法一:
// 删除ArrayList中重复元素,保持顺序
public static void removeDuplicateWithOrder(List list) {
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = list.iterator(); iter.hasNext();) {
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
list.clear();
list.addAll(newList);
System.out.println( ” remove duplicate ” + list);
}
方法二:
public static ArrayList removeDuplicate(ArrayList al){
ArrayList newAl = new ArrayList();
for(Iterator it = al.iterator(); it.hasNext();)
{
Object obj = it.next();
if(!newAl.contains(obj))
{
newAl.add(obj);
}
}
return newAl;
}
Post a comment now »
本文目前不可评论
Sorry, the comment form is closed at this time.
No comments yet.