Skip to content
Advertisement

How to design a method that has no `unchecked cast` warning in java

I have a class named Myclass, which is just a wrapper of a HashMap, I want to be able to store the possible key/value pair listed below:

  • KEY_A -> MyClassA
  • KEY_LIST_B -> List<MyClassB>
  • KEY_C -> List<MyClassC>

Here is my code :

JavaScript
  1. How can I design (signature of these methods) the get() and set() methods of MyClass to be able to store the key/value pair listed earlier and avoid the Unchecked cast?

  2. Why this line does not have Unchecked cast warning even if the cast is not safe ?

    MyClassA a = (MyClassA) myClass.get(MyEnum.KEY_A);

Advertisement

Answer

A typical solution would be to use a generic “key class” that carries information regarding the value type. Instances of the key would have a reference to the value type’s Class. Note your enum is close to this solution, but unfortunately you can’t have a generic enum where each constant has different type arguments.

Here’s an example:

JavaScript

I personally would be okay with this implementation, as the (suppressed) warnings only occur inside Container. Code which uses the Container class won’t encounter unchecked cast or raw type warnings.

The reason for the @SuppressWarnings annotations is because a Class cannot legitimately represent a parameterized type. In other words, you can have a Class<List> but not a Class<List<Foo>>1. However, if you want to avoid even suppressing these warnings, then the only approach I can think of is to create wrapper classes for your generic value types. Such as:

JavaScript

And then have a Key<MyClassBList>.

As for why:

JavaScript

Does not cause an “unchecked cast” warning to be omitted, that’s because there’s no generics involved. If the above cast is not possible at run-time, then a ClassCastException would be thrown. But when generics are involved, then the cast might succeed even if you “change” the type arguments. For instance:

JavaScript

And that mess of a situation is why they warn you about “unchecked casts”. The Container example above should not be able to result in such problems due to how put and get are defined, unless you deliberately and explicitly try to break things (e.g., by using raw types, casting “hacks”, etc.).


1. You technically can have a reference to a Class<List<Foo>>, by doing something similar to what I did with Key above, but it would not actually represent a List<Foo>.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement