问题描述
我有一个这样的变量:
List<Double> frameList = new ArrayList<Double>();
/* Double elements has added to frameList */
如何在 Java 中从该变量中获得一个具有 double[]
类型的新变量并具有高性能?
How can I have a new variable has a type of double[]
from that variable in Java with high performance?
推荐答案
高性能 - 每个 Double
对象包装一个 double
值.如果要将所有这些值存储到 double[]
数组中,则必须遍历 Double
实例的集合.O(1)
映射是不可能的,这应该是你能得到的最快的:
High performance - every Double
object wraps a single double
value. If you want to store all these values into a double[]
array, then you have to iterate over the collection of Double
instances. A O(1)
mapping is not possible, this should be the fastest you can get:
double[] target = new double[doubles.size()];
for (int i = 0; i < target.length; i++) {
target[i] = doubles.get(i).doubleValue(); // java 1.4 style
// or:
target[i] = doubles.get(i); // java 1.5+ style (outboxing)
}
感谢您在评论中提出的其他问题;) 这是拟合 ArrayUtils#toPrimitive
方法的源代码:
public static double[] toPrimitive(Double[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_DOUBLE_ARRAY;
}
final double[] result = new double[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].doubleValue();
}
return result;
}
(相信我,我的第一个答案并没有使用它 - 即使它看起来......非常相似:-D)
(And trust me, I didn't use it for my first answer - even though it looks ... pretty similiar :-D )
顺便说一句,Marcelos 答案的复杂度是 O(2n),因为它迭代了两次(在幕后):首先从列表中生成一个 Double[]
,然后解开double
值.
By the way, the complexity of Marcelos answer is O(2n), because it iterates twice (behind the scenes): first to make a Double[]
from the list, then to unwrap the double
values.
这篇关于如何从 List<Double> 投射在Java中加倍[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!