Is there an insertion order preserving Set that also implements List?

LinkedHashSet is the answer.

Iteration ordering and uniqueness.

http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html


Do you means like LinkedHashSet? This preserves the order of entry, but doesn't allow duplicates.

IMHO, its an unusual requirement but you can write a List without duplicates.

class SetList<T> extends ArrayList<T> {
    @Override
    public boolean add(T t) {
        return !super.contains(t) && super.add(t);
    }

    @Override
    public void add(int index, T element) {
        if (!super.contains(element)) super.add(index, element);
    }

    @Override
    public boolean addAll(Collection<? extends T> c) {
        boolean added = false;
        for (T t : c)
            added |= add(t);
        return added;
    }

    @Override
    public boolean addAll(int index, Collection<? extends T> c) {
        boolean added = false;
        for (T t : c)
            if (!super.contains(t)) {
                super.add(index++, t);
                added = true;
            }
        return added;
    }
}

TreeSet is sorted by element order; LinkedHashSet retains insertion order. Hopefully one of those is what you were after.

You've specified that you want to be able to insert at an arbitrary location, I suspect you'll have to write your own - just create a class containing a HashSet<T> and an ArrayList<T>; when adding an item, check whether or not it's in the set before adding it to the list.

Alternatively Apache's commons-collections4 offers ListOrderedSet and SetUniqueList, which behave similarly and should meet the given requirements.