Question

How do you store primitive numbers in Java lists? When I try to do

List<double> list = new ArrayList<>();

The compiler tells me that double isn't an object. It seems that the Collections weren't made for primitives. My clumsy workaround is as follows:

List<Double> list = new ArrayList<>();

But this is slower and uses more memory. Is there a better way to do this?

Was it helpful?

Solution

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.

OTHER TIPS

You can't use collections with primitives. You can only store objects in collections. Those objects will be unboxed automatically.

This is only way what it can be done.

You can get more info from this link: http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

There is no better way. At least Java provides automatic conversions back and forwards between e.g. double and Double to make this less painful ('autoboxing' / 'autounboxing' as it is known)

No, there's no better way. Instances of Collection can only hold onto objects, not primitives. So your workaround is the way to go.

Unless you are coding a time critical component, wondering about memory usage and/or performance in this case might indicate you are victime of premature optimization.

You can use a collection. double is not an Object but Double it is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top