在前面的一篇讨论中已经指出了ArrayList的contains方法也是效率比较低的,应该尽量避免使用它!这里有一个很实际的问题,就是已经有一个ArrayList,我要除去其中相同的元素,也就是希望得到一个不存在重复元素的List! 
这里同样使用两种方法: 1.生成一个新的ArrayList,添加之前看是否包含。 2.直接利用HashSet(HashMap的一个视图),然后返回一个ArrayList。
  
public class Test {   private static List testContains(List l) {   List list = new ArrayList(100);   for (int i = 0; i < l.size(); i++) {     Object o = l.get(i);     if (!list.contains(o)) {       list.add(o);     }   }   return list; } 
private static List testSet(List l) {   return new ArrayList(new HashSet(l)); } 
public static void test(int total, int cnt) {   long t1, t2;   List l = new ArrayList();   for (int i = 0; i < cnt; i++) {     l.add(new Integer(i));   }   t1 = System.currentTimeMillis();   for (int i = 0; i < total / cnt; i++) {     testContains(l);   }   t2 = System.currentTimeMillis();   long a = t2 - t1; 
  t1 = System.currentTimeMillis();   for (int i = 0; i < total / cnt; i++) {     testSet(l);   }    t2 = System.currentTimeMillis();   long b = t2 - t1;   System.out.println("List Size:" + cnt);   System.out.println("using Contains:" + a + "ms");   System.out.println("using Set:" + b + "ms");   System.out.println("Contains VS Set:" + (double) a / b + ":1"); } 
public static void main(String[] args) {   int total = 100 * 1000;   int cnt = 1; 
  while (cnt < total) {     test(total, cnt);     cnt *= 10;   } 
}  
看一下输出结果: 
List Size:1 using Contains:94ms using Set:203ms Contains VS Set:0.4630541871921182:1 List Size:10 using Contains:47ms using Set:47ms Contains VS Set:1.0:1 List Size:100 using Contains:172ms using Set:47ms Contains VS Set:3.6595744680851063:1 List Size:1000 using Contains:1625ms using Set:46ms Contains VS Set:35.32608695652174:1 List Size:10000 using Contains:16047ms using Set:94ms Contains VS Set:170.7127659574468:1
  当ArrayList的大小超过100,差别就比较明显,不知道有没有想过用删除的方法,直接在列表中删除重复的元素! for(int i=0;i<l.size();i++){   if (indexOf(l.get(i))!=lastIndexOf(l.get(i))){     l.remove(i);   } } 这样确实也可行呀,能想到这个方法还真不容易呢!除非你嫌你的CPU太快,否则根本不用考虑。这里同时调用了三个效率低下的方法:indexOf,lastIndexOf,remove。  
 
  |