简体   繁体   中英

How can I avoid SuppressWarnings(“unchecked”) in this generic method?

How can I get rid of @SuppressWarnings("unchecked") in this method?

@SuppressWarnings("unchecked")
public <T> Worker<T> findSimilarWorker(Worker<T> worker) {
    // The variable workers is a Set<Worker<?>>
    for(Worker<?> w : workers) {
        // The following line is unchecked cast
        if(w.isSimilar(worker)) return (Worker<T>) w;
    }

    return null;
}

As long as workers is defined to yield Worker s of type ? , you're simply going to need the type cast. The compiler is right in warning you about this, as workers might contain a Worker of a different type (though workers is not shown, I'm assuming its not of type T ).

(short version: you can't, not even with an instanceof check, which doesn't allow generics)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM