Collections.sort方法引发类java.lang.Integer不能强制转换为类java.lang.Double错误 [英] Collections.sort method is throwing class java.lang.Integer cannot be cast to class java.lang.Double error
问题描述
我从基于空手道的API自动化中的JSON响应中获取了一些运行时值.我将它们存储到ArrayList中,如:
I am getting some runtime values from a JSON response in my Karate based API Automation. I am storing them into an ArrayList like:
* def ArrayList = Java.type('java.util.ArrayList')
* def Collections = Java.type('java.util.Collections')
ArrayList al = new ArrayList();
* eval for(var i = 0; i < actualPrice.length; i++) expectedPrice.add(actualPrice[i])
当我打印列表时,输出为:
When I printed the list, the output was :
[-150,-210,-100,-112.5]
[-150, -210, -100, -112.5]
在输出上方,当我在Collections.sort(al)的帮助下申请进行排序时,它引发了以下错误:
Above output, When I applied to sort with the help of Collections.sort(al), It threw me the following error:
class java.lang.Integer cannot be cast to class java. lang.Double (java.lang.Integer and java.lang. Double is in module java.base of loader.
我需要在空手道功能文件中使用Asc/Desc排序.有人可以帮我吗?
I need to use Asc/Desc sorting in the Karate feature file. Can someone please help me here?
Java等效代码为:
Java Equivalent Code is:
ArrayList al = new ArrayList();
al.add(-150);
al.add(-210);
al.add(-100);
al.add(-112.5);
System.out.println(al);
Collections.sort(al);
推荐答案
您要将 Integer
s和 Double
s都添加到同一 List
.当排序方法尝试将 Integer
与 Double
进行比较时,它将尝试将 Integer
转换为 Double
,失败了.
You are adding both Integer
s and Double
s to the same List
. When the sorting method attempts to compare an Integer
to a Double
it attempts to cast an Integer
to a Double
, which fails.
不要使用原始类型.如果您需要向 List
中添加双精度值,请使用 List< Double>
:
Don't use raw types. If you need to add double values to the List
, use a List<Double>
:
List<Double> al = new ArrayList<>();
al.add(-150.0);
al.add(-210.0);
al.add(-100.0);
al.add(-112.5);
System.out.println(al);
Collections.sort(al);
这样, List
中的所有元素都将具有相同的类型,并且 Collections.sort()
彼此比较不会有问题.
This way all the elements of your List
will be of the same type, and Collections.sort()
won't have trouble comparing them to each other.
这篇关于Collections.sort方法引发类java.lang.Integer不能强制转换为类java.lang.Double错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!