I'm working on a List
implementation. Because of this, I'll have to override the methods
Collection.containsAll(Collection<?> c);
Collection.removeAll(Collection<?> c);
Collection.retainAll(Collection<?> c);
But as it's explained by Sun, they accept collections with any kind of content (note the <?>
). So the collection is not checked by the compiler and it's up to me, to check it. But how to do it? instanceof
on each element won't work because of type erasure. The next solution would be to cast each element an catch the ClassCastException
. Look here:
public boolean containsAll( Collection<?> c ) {
boolean foundAll = true;
for ( Object element : c ) {
try {
foundAll &= this.contains( (T) element );
} catch ( ClassCastException e ) {
foundAll = false;
}
}
return foundAll;
}
The other two methods look similar. That works. But it gives me compiler warning "warning: [unchecked] unchecked cast"! Unless I suppress it with "@SuppressWarnings("unchecked")
", it won't compile fine.
I don't want to rely on "@SuppressWarnings("unchecked")
" unless I really have to. Is there a way to avoid it? How would you implement those methods like containsAll(Collection<?> c)
?
edit
Ok, sorry guys, I was not clear enough. I don't extend AbstractList
, and I don't want to. My list is implemented by a balanced binary tree. I have an own implementation of insert()
, remove()
, contains()
(that actually does a search for the leaf), etc, and all take an argument of (generic) type T
. The key goal is to have a sorted list that can be modified while it's iterated through.
So... how do I avoid the warning in containsAll(Collection <?>)
? I have to cast!
Thanks! craesh