简体   繁体   English

寻找更好的方法来转换ArrayList <Double> 加倍[]数组

[英]Looking for a better way to convert ArrayList<Double> to double[] array

I've been searching a solution for converting an ArrayList to a double[] array. 我一直在寻找将ArrayList转换为double []数组的解决方案。 After reading a few questions on the same issue, i figure out a solution. 在阅读了同一问题的几个问题后,我找到了解决方案。 This is how i work now. 这就是我现在的工作方式。

  public static double[] listToArray(List<Double> arr){   
  double[] result = new double[arr.size()];
  Iterator<Double> itr = arr.iterator();
  int i = 0 ; 
  while(itr.hasNext()){
      try{
          result[i] = Double.parseDouble(itr.next().toString());
          i++;
      }catch(IndexOutOfBoundsException e){
          System.out.println("OutOfBouds");
      }
  }      
  return result;
  }

This is a rather nasty way. 这是一种相当令人讨厌的方式。 I know there are some APIs that can do what i want. 我知道有一些API可以做我想要的。 But in that case, i will bring extra complexity to my project, which is not what i want to see. 但在这种情况下,我会为我的项目带来额外的复杂性,这不是我想要看到的。 Can anyone give me a better solution?? 谁能给我一个更好的解决方案?

public static double[] listToArray(List<Double> arr){   
    double[] result = new double[arr.size()];
    int i = 0;
    for(Double d : arr) {
        result[i++] = d.doubleValue();
    }
    return result;
}

Well, there is: .toArray() but that will get you an array of Double objects. 好吧,有: .toArray()但是会得到一个Double对象数组。

Try: 尝试:

ArrayList<Double> objList;
double[] primList = new double[objList.size()];
for (int i =0; i < objList.size(); ++i)
   primList[i] = objList.get(i);
double[] test(final List<Double> sourcelist) {
    if (sourcelist==null) {
        return null;
    }
    double[] array = new double[sourcelist.size()];
    int i = 0;
    for (Double value : sourcelist) {
        if (value == null) {
            array[i++] = 0D; // or some other null representation
        } else {
            array[i++] = value.doubleValue();
        }
    }
    return array;
}

Here is how Apache Commons Lang doit 以下是Apache Commons Lang的工作方式

org.apache.commons.lang.ArrayUtils: org.apache.commons.lang.ArrayUtils:

    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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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