@Override public E set(int index, E element) { if (contains(element)) { // Element already exist in the list if (get(index) == element) { // At the same position, nothing to be done return element; } else { // Adding at another position. We assume this is a sort // operation and temporarily allow it. // We could just remove (null) the old element and keep the list // unique. This would require finding the index of the old // element (indexOf(element)) which is not a fast operation in a // list. So we instead allow duplicates temporarily. addDuplicate(element); } } E old = super.set(index, element); removeFromSet(old); itemSet.add(element); return old; }