Unchecked Assignment Java Generics Pdf

The reason what you've shown is unsafe is that with this assignment:

does not need to have anything to do with the retrieved from the map. is always inferred from the surrounding context of the call to . For example I can do this sequence of calls:

Inside the method, is correctly retrieved from the type map, but an unchecked conversion is made to . The call to doesn't throw, because the value retrieved from the data map is a . An implicit checked cast then actually happens to the return value, casting it to and a is thrown.

This strange interaction is due to type erasure.

So, when we are storing multiple types in a single data structure, there are a number of ways to approach it, depending on what our needs are.

1. We can forego compilation checks if there is no way to perform them.

Storing the is pointless for the most part here because, as I showed above, it doesn't perform a useful validation. So we could redesign the map along the following lines:

and do a similar thing but:

In both cases we're just relying on our own awareness as a programmer to not make mistakes.

Suppressing warnings isn't necessarily bad, it's just important to understand what they actually mean and what the implications are.

2. Pass a to so the return value must be valid.

This is the way I've seen it done typically.

But, of course, it means we need to pass two parameters to .

3. Parameterize the keys.

This is a novel but more advanced and it may or may not be more convenient.

So e.g.:

This might make sense if the entries are known or predictable so we can have something like:

Then we don't have to construct a key object any time a retrieval is done. This works very well especially for adding some strong typing to stringly-typed scenarios.

4. Don't have a map any kind of object can be put in, use polymorphism of some kind.

When possible and not too cumbersome, it's a good option. If there is a common behavior that the different types are used for, make it an interface or superclass so we don't have to use casting.

A simple example might be like this:

And we could instead substitute something like this:

Бизнес - это война, с которой ничто не сравнится по остроте ощущений. Хотя три дня назад, когда раздался звонок, Токуген Нуматака был полон сомнений и подозрений, теперь он знал правду. У него счастливая миури - счастливая судьба. Он избранник богов.


Leave a Reply

Your email address will not be published. Required fields are marked *