Convert a double array to Double ArrayList

若如初见. 提交于 2019-12-18 03:54:40

问题


When I try to convert a double array to a Double arrayList I got the following error:

Exception in thread "main" java.lang.ClassCastException: [D cannot be cast to java.lang.Double

Below is my code.

double [] firstValueArray ;

ArrayList <Double> firstValueList = new ArrayList (Arrays.asList(firstValueArray));

I am comparing this list with another list and assign the result to another double variable.

Please let me know the reason for this error.


回答1:


Alas, Arrays.asList(..) doesn't work with primitives. Apache commons-lang has

Double[] doubleArray = ArrayUtils.toObject(durationValueArray);
List<Double> list = Arrays.asList(doubleArray);



回答2:


Using Java 8 Streams API this is achieved with

DoubleStream.of(doublesArray).boxed().collect(Collectors.toList());

If returning an ArrayList as an implementation is required then use

DoubleStream.of(doublesArray).boxed().collect(Collectors.toCollection(ArrayList::new));

This one-liner doesn't require any additional libraries.




回答3:


Guava's version is even shorter:

List<Double> list = Doubles.asList(doubleArray);

Reference:

  • Doubles.asList(double ...)

Note: This is a varargs method. All varargs methods can be called using an array of the same type (but not of the corresponding boxed / unboxed type!!). These two calls are equivalent:

Doubles.asList(new double[]{1d,2d});
Doubles.asList(1d,2d);

Also, the Guava version doesn't do a full traverse, it's a live List view of the primitive array, converting primitives to Objects only when they are accessed.




回答4:


Credit to bestsss for the comment which should be the answer:

ArrayList<Double> firstValueList = new ArrayList<Double>();
for(double d : firstValueArray) firstValueList.add(d);



回答5:


…or with Java 1.7:

double[] firstValueArray = new double[] {1.0, 2.0, 3.0};

ArrayList<Double> list = DoubleStream.of( firstValueArray ).boxed().collect(
    Collectors.toCollection( new Supplier<ArrayList<Double>>() {
      public ArrayList<Double> get() {
        return( new ArrayList<Double>() );
      }
    } ) );


来源:https://stackoverflow.com/questions/5178854/convert-a-double-array-to-double-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!