如何将 Double[] 转换为 double[]? [英] How do I convert Double[] to double[]?

查看:68
本文介绍了如何将 Double[] 转换为 double[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个接口,该接口的功能类似于可以包含某种类型对象的表.接口指定如下函数:

I'm implementing an interface that has functionality similar to a table that can contain an types of objects. The interface specifies the following function:

double[] getDoubles(int columnIndex);

让我感到困惑的是,在我的实现中,我将表数据存储在一个二维 Object 数组(Object[][] data)中.当我需要返回值时,我想执行以下操作(假设 getDoubles() 只会在包含双精度的列上调用,因此不会有 ClassCastExceptions):

Where I'm stumped is that in my implementation, I'm storing the table data in a 2D Object array (Object[][] data). When I need to return the values, I want to do the following (it is assumed that getDoubles() will only be called on a column that contains doubles, so there will be no ClassCastExceptions):

double[] getDoubles(int columnIndex) {
    return (double[]) data[columnIndex];
}

但是 - Java 不允许将 Object[] 转换为 double[].将它转换为 Double[] 是可以的,因为 Double 是一个对象而不是一个原始类型,但我的接口指定数据将作为 double[]<返回/代码>.

But - Java doesn't allow Object[] to be cast to double[]. Casting it to Double[] is ok because Double is an object and not a primitive, but my interface specifies that data will be returned as a double[].

所以我有两个问题:

  1. 有什么办法可以从 Object[][] 表中取出列数据并返回原语数组?
  2. 如果我确实将接口更改为返回 Double[],是否会影响性能?
  1. Is there any way I can get the column data out of the Object[][] table and return the array of primitives?
  2. If I do change the interface to return Double[], will there be any performance impact?

推荐答案

不幸的是,如果要将 Double 转换为 double,您需要遍历整个列表并取消装箱[].

Unfortunately you will need to loop through the entire list and unbox the Double if you want to convert it to a double[].

就性能而言,Java 中的装箱和拆箱原语需要一些时间.如果集合足够小,您就不会看到任何性能问题.

As far as performance goes, there is some time associated with boxing and unboxing primitives in Java. If the set is small enough, you won't see any performance issues.

这篇关于如何将 Double[] 转换为 double[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆