将双精度数组转换为双精度 ArrayList
当我尝试将双精度数组转换为双精度数组列表时,出现以下错误:
线程“main”中的异常 java.lang.ClassCastException: [D 无法转换为 java.lang.Double
下面是我的代码。
double [] firstValueArray ;
ArrayList
我正在将此列表与另一个列表进行比较,并将结果分配给另一个双变量。
请让我知道这个错误的原因。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
唉,
Arrays.asList(..)
不适用于基元。 Apache commons-lang 有Alas,
Arrays.asList(..)
doesn't work with primitives. Apache commons-lang has使用 Java 8 Streams API 可以实现这一点
。从 java 16 开始,这变得更加简洁:
如果需要返回 ArrayList 作为实现,则使用
此单行代码不需要任何其他库。
Using Java 8 Streams API this is achieved with
Since java 16 this became a bit more concise:
If returning an
ArrayList
as an implementation is required then useThis one-liner doesn't require any additional libraries.
Guava 的版本更短:
参考:
Doubles.asList(double ...)
注意:这是一个可变参数方法。所有可变参数方法都可以使用相同类型的数组来调用(但不是相应的装箱/未装箱类型!!)。这两个调用是等效的:
此外,Guava 版本不执行完整的遍历,它是基元数组的实时列表视图,仅在访问基元时将基元转换为对象。
Guava's version is even shorter:
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:
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.
感谢 bestsss 的评论,这应该是答案:
Credit to bestsss for the comment which should be the answer:
…或者使用 Java 1.7:
…or with Java 1.7: