How do I remove repeated elements from ArrayList?

后端 未结 30 1605
难免孤独
难免孤独 2020-11-21 06:24

I have an ArrayList, and I want to remove repeated strings from it. How can I do this?

30条回答
  •  无人及你
    2020-11-21 06:35

    Probably a bit overkill, but I enjoy this kind of isolated problem. :)

    This code uses a temporary Set (for the uniqueness check) but removes elements directly inside the original list. Since element removal inside an ArrayList can induce a huge amount of array copying, the remove(int)-method is avoided.

    public static  void removeDuplicates(ArrayList list) {
        int size = list.size();
        int out = 0;
        {
            final Set encountered = new HashSet();
            for (int in = 0; in < size; in++) {
                final T t = list.get(in);
                final boolean first = encountered.add(t);
                if (first) {
                    list.set(out++, t);
                }
            }
        }
        while (out < size) {
            list.remove(--size);
        }
    }
    

    While we're at it, here's a version for LinkedList (a lot nicer!):

    public static  void removeDuplicates(LinkedList list) {
        final Set encountered = new HashSet();
        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
            final T t = iter.next();
            final boolean first = encountered.add(t);
            if (!first) {
                iter.remove();
            }
        }
    }
    

    Use the marker interface to present a unified solution for List:

    public static  void removeDuplicates(List list) {
        if (list instanceof RandomAccess) {
            // use first version here
        } else {
            // use other version here
        }
    }
    

    EDIT: I guess the generics-stuff doesn't really add any value here.. Oh well. :)

提交回复
热议问题