I know about SortedSet, but in my case I need something that implements List
, and not Set
. So is there an implementation out there, in the API or e
NOTE: it does not take subList implementation into account.
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class UniqueList extends ArrayList {
private static final long serialVersionUID = 1L;
/** Unique elements SET */
private final Set set=new HashSet();
/** Used by addAll methods */
private Collection addUnique(Collection extends T> col) {
Collection unique=new ArrayList();
for(T e: col){
if (set.add(e)) unique.add(e);
}
return unique;
}
@Override
public boolean add(T e) {
return set.add(e) ? super.add(e) : false;
}
@Override
public boolean addAll(Collection extends T> col) {
return super.addAll(addUnique(col));
}
@Override
public void add(int index, T e) {
if (set.add(e)) super.add(index, e);
}
@Override
public boolean addAll(int index, Collection extends T> col) {
return super.addAll(index, addUnique(col));
}
}