K.Barad
K.Barad

Reputation: 1016

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
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.

Upvotes: 0

Views: 138

Answers (2)

Philipp Wendler
Philipp Wendler

Reputation: 11433

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);

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308001

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.

Upvotes: 3

Related Questions