今天,在开发的时候遇到了去掉list中的重复值,去掉重复的值分为两种情况:
1.对原来list顺序不要求
public static void removeDuplicate(ArrayList arlList)
{
HashSet h = new HashSet(arlList);
arlList.clear();
arlList.addAll(h);
}
2.对原来list顺序不变
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);
}
这里主要用了set add API 的作用当有了重复值时,返回false