简体   繁体   English

将double数组转换为Double ArrayList

[英]Convert a double array to Double ArrayList

When I try to convert a double array to a Double arrayList I got the following error: 当我尝试将双数组转换为Double arrayList时,我收到以下错误:

Exception in thread "main" java.lang.ClassCastException: [D cannot be cast to java.lang.Double 线程“main”中的异常java.lang.ClassCastException:[D不能强制转换为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. 请让我知道此错误的原因。

Alas, Arrays.asList(..) doesn't work with primitives. 唉, Arrays.asList(..)不适用于基元。 Apache commons-lang has Apache commons-lang有

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

Guava 's version is even shorter: 番石榴的版本更短:

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

Reference: 参考:

Note: This is a varargs method. 注意:这是一种varargs方法。 All varargs methods can be called using an array of the same type (but not of the corresponding boxed / unboxed type!!). 可以使用相同类型的数组(但不是相应的盒装/非盒装类型!!)调用所有varargs方法。 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. 此外,Guava版本不进行完整遍历,它是原始数组的实时List视图,仅在访问它们时将原语转换为Objects。

Using Java 8 Streams API this is achieved with 使用Java 8 Streams API可以实现

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

If returning an ArrayList as an implementation is required then use 如果需要返回ArrayList作为实现,则使用

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

This one-liner doesn't require any additional libraries. 这种单行程不需要任何额外的库。

Credit to bestsss for the comment which should be the answer: 感谢评论的最佳人选应该是答案:

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

…or with Java 1.7: ...或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>() );
      }
    } ) );

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

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