I have an ArrayList of enums but I need to make sure that there is only one of a particular enumeral (or whatever it's called). Should I make a new class that extends ArrayList and checks the input? I've seen that maybe it's best not to (Can you extend ArrayList in Java?) but I can't see a better way.
my enum
enum myEnum{
SPECIAL,
OTHER1,
OTHER2,//etc
}
with ArrayList
List<myEnum> list = new ArrayList<>();
list.add(myEnum.SPECIAL);
list.add(myEnum.OTHER1);
list.add(myEnum.SPECIAL);//OH NO!!!
without ArrayList
class myList extends ArrayList<myEnum> {
@Override
public boolean addAll(int i, Collection<? extends myEnum> clctn) {
if(check()){
super.addAll(i, clctn);
}else{
//do something or throw error;
}
}
@Override
public boolean addAll(Collection<? extends myEnum> clctn) {
if(check()){
super.addAll(clctn);
}else{
//do something or throw error;
}
}
@Override
public void add(int i, myEnum e) {
if(check()){
super.add(i, e);
}else{
//do something or throw error;
}
}
@Override
public boolean add(myEnum e) {
if(check()){
return super.add(e);
}else{
//do something or throw error;
}
}
boolean check(){
//do stuff
}
}
myList list = new myList();
list.add(myEnum.SPECIAL);
list.add(myEnum.OTHER1);
list.add(myEnum.SPECIAL);//something happens or error is thrown
Is there a better way or is this acceptable?