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

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


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/doodoofish/archive/2004/05/07/17922.aspx

http://www.blogjava.net/Johncn/archive/2005/08/18/10404.html

你可能感兴趣的:(list,object,iterator)