Unchecked cast: Is there a way to avoid it in this case?
I have a situation that is causing an unchecked cast warning. I know I can use supress warnings, but my instinct tell me there is a way to avoid it by changing how I've coded this snippet. I can't, however, seem to get the solution to surface and could do with a fresh set of eyes.
//function removes elements from input, orders them and re-adds them开发者_如何学JAVA
private <E extends Bus> int orderBuses(ArrayList<E> busList) {
Bus busToAdd = null;
...
busList.add((E) busToAdd);
return 0;
}
The function is called with several lists, each containing a class that extends Bus. Several functions are used on busToAdd that are part of Bus so using type E wouldnt work.
Any suggestions on how to restructure this without having to suppress warnings?
edit: Found I can use E for busList, but end up having to cast the buses I assign to it which leads to the same warning. I can try using E for all uses instead of Bus, I'll update when I have tested it.
Why wouldn't using E
not work here?
You say that you're using some methods that are part of Bus
, but since E extends Bus
you should be able to call all of Bus
' methods on E
as well.
You should be able to replace references to the type Bus
by E
in the body of your method. Then there would be no warning.
Example:
E busToAdd = busList.get(0);
// ...
busList.add(busToAdd);
精彩评论