Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to best store a list of primitive values? [duplicate]

Tags:

java

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?

like image 432
Fischer Ludrian Avatar asked Nov 24 '25 15:11

Fischer Ludrian


2 Answers

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.

like image 160
LionC Avatar answered Nov 27 '25 05:11

LionC


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.

like image 44
er_suthar Avatar answered Nov 27 '25 05:11

er_suthar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!