开发者

Casting Objects to <T>-type

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 MyCollecti开发者_运维问答on<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;
}


Is it the right approach ?

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 addAll should return a boolean. Also, you dont need to cast in addAll that you have implemented. Change your loop instead:

   for(T o : c){...}

And your retainAll should be fine as well, as long as you return a boolean.

EDIT:

For your retainAll implementation, there shouldn't be a need to iterate over the passed in Collection<?> and cast to a T. Consider iterating over your tab backing array and seeing if each instance is contained in the passed in Collection<?> c. If for some reason you absolutely need to use the items within c as Ts, you can cast.


You should be defining your addAll method like this:

public boolean addAll(Collection<? extends T> c) {...}

That's how it's defined in the Java API


Casting to T is not required to implement retainAll(...). For example:

public boolean retainAll(Collection<?> c){
    boolean result = false;
    Iterator<T> it = this.iterator();
    while (it.hasNext()) {
        T t : it.next();
        if (!c.contains(t)) {
            it.remove();
            result = true;
        }
    }
    return result;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜