Eduardo
Eduardo

Reputation: 7141

Store Long[] and Integer[] in the same HashMap using Generics

I need to store arrays of different types of numerical data in a HashMap. Each array is a measurable variable such as temperature and I need to store the variables name and unit with the array so I made the class below:

public class Variable <T> {

    public T[] array;
    public String name;
    public String unit;

    ......etc

}

I want to be able to save Integer[], Double[] and Long[] which is why I used the generic <T>. I have tried using public Number[] array instead but this does not let me save different types.

I have tried to store these in a HashMap<String,Variable<Number>> map using:

Variable<Long> temperature = new Variable<Long>();
map.put(temperature.name, temperature);

but I get the error:

The method put(String, Variable<Number>) in the type
HashMap<String,Variable<Number>> is not applicable for the arguments
(String, Variable<Long>)

How can I fix this?

Upvotes: 0

Views: 371

Answers (2)

Keppil
Keppil

Reputation: 46229

Even though Long is a subclass of Number, Variable<Long> is not a subclass of Variable<Number>. This operation simply does not work with generics.

With a HashMap<String,Variable<? extends Number>>, you would be able to put() a Variable<Long>. You would not be able to retrieve it as such without an unsafe cast though, since the retrieved type would be Variable<? extends Number>.

Upvotes: 4

kajacx
kajacx

Reputation: 12939

You can use wildcards to help you:

Map<String, Variable<? extends Number>> map = new HashMap<>();
Variable<Long> varLong = new Variable<>(new Long[]{5L});
map.put("long", varLong);
Number number = map.get("long").array[0];
System.out.println(number.doubleValue());

Prints out: 5.0

Upvotes: 4

Related Questions