I am not sure how clear the title is. I am working on creating an ArrayList
(specifically for String
s) in Java, and I want to merge removeAll()
and retainAll()
into one method. This is what I have:
@Override
public boolean removeAll(Collection<?> c) {
return removeSome(c, true);
}
@Override
public boolean retainAll(Collection<?> c) {
return removeSome(c, false);
}
And for the method itself:
private boolean removeSome(Collection<? extends String> c, boolean remove) { //remove vs retain
collectionIsNullCheck(c);
if (c.isEmpty()) {
return false;
}
int newInsertionPoint = 0;
boolean changed = false;
for (int i = 0; i < insertionPoint; i++) {
if (remove) { //remove
if (!c.contains(backingStore[i])) {
backingStore[newInsertionPoint++] = backingStore[i];
//this check is here because maybe backingStore and c don't intersect
if (!changed)
changed = true;
}
} else { //retain
if (c.contains(backingStore[i])) {
backingStore[newInsertionPoint++] = backingStore[i];
if (!changed)
changed = true;
}
}
}
Arrays.fill(backingStore, newInsertionPoint, backingStore.length - 1, null);
insertionPoint = newInsertionPoint;
return changed;
}
What I am curious about is whether there is some way to not duplicate the entire code block of
if (!c.contains(backingStore[i])) {
backingStore[newInsertionPoint++] = backingStore[i];
//this check is here because maybe backingStore and c don't intersect
if (!changed)
changed = true;
}
I considered something like
if ((remove && !c.contains(backingStore[i])) || (!remove && c.contains(backingStore[i]))) {
...
}
But I was wondering if there is a better way.
Aucun commentaire:
Enregistrer un commentaire