I’m implementing List interface to a class which stores data in a <T> type array. This raises problems with methods that take Collection as parameters, since collection stores it’s objects as Object. How can I transform Object to T ? Simple casting doesn’t work.
class MyCollection<T> implements List<T>{
T[] tab;
MyCollection() {
this.tab = (T[])new Object[10];
}
public boolean addAll(Collection c){
for(Object o : c){
o = (T)o;
for(int i = 0; i < tab.length; i++){
tab[i] = o;
}
}
}
}
I’m trying :
public boolean addAll(Collection<? extends T> c)
but it fails with :
public boolean retainAll(Collection<?> c) since I cannot change the Collection type here :/
public boolean retainAll(Collection<?> c){
boolean result = false;
for(T t : c){
}
return result;
}
Yes, that is correct approach. That is what the interface is defined as (except that the interface uses
E, but that doesn’t matter).Note that your
addAllshould return aboolean. Also, you dont need to cast inaddAllthat you have implemented. Change your loop instead:And your
retainAllshould be fine as well, as long as you return aboolean.EDIT:
For your
retainAllimplementation, there shouldn’t be a need to iterate over the passed inCollection<?>and cast to aT. Consider iterating over yourtabbacking array and seeing if each instance is contained in the passed inCollection<?> c. If for some reason you absolutely need to use the items withincasTs, you can cast.