A question about generics and autoboxing/unboxing

F

François Grondin

Hi everyone

Does anyone has an explanation why one can't define a list of numbers using
generics AND basic number types? I mean for example
List<double> list = new ArrayList<double>();

I know that the normal way to do it would be using wrappers :
List<Double> list = new ArrayList<Double>();

I can use the fact that autoboxing and unboxing will convert from wrapper to
basic type. But my concern is that I have to develop an application that
does a lot of numerical computations, and calculation speed IS an important
issue.

When I read about autoboxing/unboxing from Sun web site, it is clearly
written that it should not be used "for scientific computing or other
performance-sensitive numerical code". If necessary, I'll work with double[]
instead, if it's my only alternative.

Any ideas?

Thanks.

François Grondin
 
L

Lew

I can't provide the canonical spec-based explanation.  However, the basic  
issue is that in Java, generics undergo "type erasure" when they are  
compiled.  That is, they are _strictly_ a compile-time thing, and the  
actual implementation always uses the exact same class.

That means that there's really only one type used in the generic type; in  
this case, "Object".  And so you have to use a type that inherits Object,  
which excludes Java's primitive types.

Even before generics, List and the other Collection types couldn't
hold primitives. Why would they start after generics?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top