Tuesday, 10 September 2013

Add an object to a java arraylist only if it isn't already there

Add an object to a java arraylist only if it isn't already there

I have an arrayList that I want to add to, as long as the value isn't
already stored in it. For example if my array is like this:
H
LK
KL
LS
And I have the value LS, it wouldn't be added. But if the value was A, it
would be.
I was thinking that the code should look something like this:
value = A;
no = 0;
for (int o; arraylist.length; o++)
if (arraylist.get(o).equals(value)){
continue;
}else{
no++;
}
}
if (arraylist.length = no){
arraylist.add(value);
}
But there has to be an easier way to do it. Does anyone know a more
concise way to do this?

No comments:

Post a Comment