Search code examples
javagenericstypechecking

Java : Class wrapper using generic


I would in some way store many different type in a HashMap, but in a way that when i extract them they will be well typed (and not an object).

So i think about a wrapper that use generics

 public class Value <T>
 {
     private T innerValue ;

     public Value ( T _value )
     {
         innerValue = _value ;
     }

     public T read ()
     {
         return innerValue ;
     }
 }

but it does not work, for a test i made :

 Value <Integer> va = new Value <Integer> ( 1 ) ;
 Value vc = va ;
 int restA = vc.read();

but i get a design time error, because vc.read() will return an Object() and not an Integer. So what should i do to avoid this behaviour? (if possible i would a solution that prevent 'va' from losing information about T instead of other workaround)

Thanks in advance for any help.


Solution

  • You casted va to a raw Value, vc. When you use the raw form of a class, your T generic type parameter is replaced by Object. So you cannot assign an Object to an int.

    If you just call va.read(), then it will return an Integer, which will be unboxed to an int upon assignment to restA.