سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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

Short answer is: this is not possible. And type erasure is not the reason: it simply does not make much sense to have this information at compile time. Suppose that Java compiler had some kind of mechanism to keep track of the types of objects stuffed into a HashMap. Then it also would have to cope with something like this:

HashMap<Integer, Value<?>> myMap = new HashMap<Integer, Value<?>>;
if (Math.random() > 0.5) {
    myMap.put(0, new Value<String>("hello world"));
} else {
    myMap.put(0, new Value<MacaroniExtruder>(new MacaroniExtruder()));
}
[whatDoYouWantToWriteHere?] value = myMap.get(0);

What you want is probably rather something like "type-union". Unfortunately, it does not exist neither in Java, nor in Scala (where we have case-classes, which are almost just as good for that). So all you can do is basically:

A) Use polymorphism, define a proper interface, so that the concrete implementations become completely irrelevant, and work with that interface as second argument to your hash Map (preferred).

B) Use instanceof and long if-else switches (ugly)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top