You cannot use primitives directly in a collection in Java. This is a deliberate design-decision in Java (though some think it is a mistake). Generics in Java were bolted on after the fact, which is why their application is not uniform across the language.
Containers basically want Object types and primitive types aren't derived from Object
(i.e., Object
is not their superclass unlike every other object in Java). From a code-writing point of view, it certainly looks like there are no wrappers:
list.add(6); //list is of type List<Integer>
int num = list.get(i);
This is because the boxing and unboxing is done automatically for you. At the bytecode level, what you actually have is:
list.add(new Integer(6));
int num = ((Integer) list.get(i)).intValue();
So the second option you have is the right way in Java.
If you want a less memory-hungry option, you can opt for a straight double[]
. However, this means that you are going to have to write code to manage add, retrieve, update, and delete operations. If that is too much extra work, you can try using Apache Commons Primitives.
Also, I suspect you meant List<Double> list = new ArrayList<>();
(or some other implementation), right? This is because what you have won't compile.