class UniqueArrayList<E> extends ArrayList<E> {
private static final long serialVersionUID = 1357048473879966517L;
public UniqueArrayList(int initialCapacity){
super(initialCapacity);
}
public UniqueArrayList(){
super();
}
// sets the given index to the given value
// if the list doesn't contain an equivalent value
@Override
public E set(int index,E e){
if(!contains(e)) {
return super.set(index,e);
}
if(indexOf(e)==index) {
return e;
}
throw new IllegalArgumentException("Cannot set a value already in the list");
}
@Override
public boolean add(E e){
if(!contains(e)) {
super.add(e);
return true;
}
return false;
}
@Override
public void add(int index,E e){
if(!contains(e)) {
super.add(index,e);
}
}
@Override
public boolean addAll(Collection<? extends E> c){
boolean someAdded = false;
for(E item : c) {
if(!contains(item)) {
super.add(item);
someAdded = true;
}
}
return someAdded;
}
@Override
public boolean addAll(int index,Collection<? extends E> c){
boolean someAdded = false;
for(E item : c) {
if(!contains(item)) {
super.add(index,item);
index++;
someAdded = true;
}
}
return someAdded;
}
}
1条答案
按热度按时间bxjv4tth1#
我很快就创建了这个自定义集合,它的行为就像一个ArrayList,但是它不允许重复,你可能需要修改它来满足你的需要。