package Medium;
import java.util.ArrayList;
import java.util.Scanner;
public class Demo5 {
public static void main(String[] args) {
System.out.println("input end when you want to stop:");
ArrayList<Double> arr = new ArrayList<Double>();
while(true){
Scanner in = new Scanner(System.in);
//String d = in.nextLine();
double d = in.nextDouble();
arr.add(d);
if (d==0) {
break;
}
}
Double[] array =(Double[]) arr.toArray(); //I hava already change the type to double
int outter,inner,max;
for(outter=0;outter<array.length-1;outter++){
max = outter;
for(inner=outter+1;inner<array.length;inner++){
if (array[inner]>array[max]) {
inner = max;
}
}
double temp =array[outter];
array[outter] =array[inner];
array[inner]=temp;
}
System.out.println(array);
}
}
描述:查找数组中第 K 大的元素。
我想输入一个 arrayList 并将其更改为数组,然后使用 selectSort。但是,在 "Double[] array =(Double[]) arr.toArray();"上打印出
,出了什么问题?谢谢您的宝贵时间。ClassCastException
异常(exception):
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Double;
at Medium.Demo5.main(Demo5.java:31)
最佳答案
不传递任何参数的 toArray
() 方法会返回 Object[]
。
为了解决这个问题,您必须将数组作为具有类型和大小的参数传递。
Double[] array = list.toArray(new Double[list.size()]);
关于java - 一个简单的 java classCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43154044/