2
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);
    }
}

Description:Find K-th largest element in an array. I want to input a arrayList and change it into array,then use selectSort.However,prints out ClassCastException on"Double[] array =(Double[]) arr.toArray();",what's wrong?thank you for your time.

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)
shizhz
  • 11,715
  • 3
  • 39
  • 49
Lucy
  • 45
  • 1
  • 1
  • 7
  • `Object[] != Double[]` – Suresh Atta Apr 01 '17 at 07:24
  • thank you..so how exactly should I changed it? – Lucy Apr 01 '17 at 07:26
  • There is a very good answer here in this link: http://stackoverflow.com/questions/5690351/java-stringlist-toarray-gives-classcastexception – Fady Saad Apr 01 '17 at 07:28
  • Possible duplicate of [java: (String\[\])List.toArray() gives ClassCastException](http://stackoverflow.com/questions/5690351/java-stringlist-toarray-gives-classcastexception) – MC Emperor Apr 01 '17 at 07:37
  • thank you..there are thounds of question similar to classCastException..how could you aim at the fit one so quickly.. – Lucy Apr 01 '17 at 07:47

2 Answers2

2

The toArray() method without passing any argument gives you back Object[].

Just to fix the issue you have to pass an array as an argument with type and size.

Double[] array =  list.toArray(new Double[list.size()]);
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

Another way to do this is:

Double[] array = Arrays.copyOf(arr.toArray(), arr.size(), Double[].class);

Either method, you need to pass the array type Double[] and its length in some way.

shizhz
  • 11,715
  • 3
  • 39
  • 49