In my Java program, I want to store a list of primitive values. I could do something like this:
int x = 0;
double timestamp = 123.1d;
List<Object> data = new ArrayList<Object>();
data.add(x);
data.add(timestamp);
But then the problem is that I do not know exactly what kind of objects i store in the list. So is there any better way to do that?
Well, Double, Integer, Long all belong to the Number-class. So a
List<Number>
would probably fit. It is exactly what it is - a List of numbers of unspecified subtype. Because of autoboxing you should be able to just add the primitives, but the better practice would be to use the Wrapper-classes.
The Number-class offers methods to get the different representations of the Number, for example doubleValue(). So you could convert all the values in the List<Number> to (as an example) Doubles by using this method. For more reference see the Oracle documentation for Number.
You could use List<Object> and add any kind of object to it.While retrieving the Object back from List<Object> you can get class of object by list.get(0).getClass() or you could check for list.get(i) instacne of Double.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With