简体   繁体   中英

Can't cast array Object to double[]

I read where an array of int can't be cast as double[]: Casting Don't Work int[] to double[], 17 Oct

I have run into a similar roadblock trying to cast an array Object of doubles to double[]. I suspect it is the same issue.

I would like to understand the limitation better. Is this a general limitation on all collections, or is it limited to arrays? Is there a fundamental reason for the limitation, or is it just something that has to be worked around?

I have a class that creates an array of doubles that represents an input signal. I pass an instance of that class to a class to calculate the FFT of the signal. The FFT class I'm using needs a double[] parameter. Since I create the input array as double[], it seems I should be able to cast it as such.

trying to cast an array Object of doubles to double[]

There is no such thing as 'an array Object of doubles' in Java. There is double[], there is Double[], and there is Object[] where the elements are Doubles.

You can cast between the last two, in both directions if the underlying type really is Double[], but not between the first and either of the others.

The problem is explained here Why covariance and contravariance do not support value type . Covariance and contravariance does not work with value types. However, you can force the cast by using linq as Will mentioned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM