高效删除ArrayList中的重复记录,不多说看代码

import java.util.ArrayList;
import java.util.List;
public class HighEffectDelete {
    public static void main(String[] args) {
        List list = new ArrayList();
        for (int i = 0; i < 1000000; i++) {
            list.add(i);
            if (i % 10 == 0)
                list.add(0);
        }
        Long start = System.currentTimeMillis();
        effectiveDelete(list, 0);
        //normalDelete(list, 0);
        System.out.println((System.currentTimeMillis() - start));
    }
    public static void normalDelete(List list, Object key) {
        for (int i = list.size() - 1; i > -1; i--) {
            if (key.equals(list.get(i)))
                list.remove(i);
        }
    }
    public static void effectiveDelete(List list, Object key) {
        int i = 0, j = 0, size = list.size();
        while (j < size) {
            Integer elem = list.get(j);
            if (key.equals(elem)) {
                for (j = j + 1; j < size && key.equals(list.get(j)); j++)
                    ;
                while (j < size) {
                    Integer o = list.get(j);
                    if (!key.equals(o)) {
                        list.set(i, o);
                        i++;
                        j++;
                    } else {
                        break;
                    }
                }
            } else {
                i++;
                j++;
            }
        }
        for (int k = size - 1; k >= i; k--) {
            list.remove(k);
        }
    }
}

 

你可能感兴趣的:(integer,list,object,import,string,class)