如何从List< Double>在Java中加倍[]? [英] How to cast from List<Double> to double[] in Java?

查看:143
本文介绍了如何从List< Double>在Java中加倍[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的变量:

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

/* Double elements has added to frameList */

有一个新的变量类型 double [] 从Java中的高性能变量?

How can I have a new variable has a type of double[] from that variable in Java with high performance?

推荐答案

高性能 - 每个 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)
 }





$ b b

感谢评论中的其他问题);这里是 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&lt; Double&gt;在Java中加倍[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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