Maduri
Maduri

Reputation: 279

What is reason for list couldn't convert into array?

I'm trying to convert List type data collection into array.

    public void method1(List s1){
    List s=s1;
    String []array = new String[s.size()];
    array=(String[])s.toArray(); 
    for(int i=0;i<array.length;i++){
        System.out.println(array[i]);
    }
    }

Then following class cast exception occurs. Error line was "array=(String[])s.toArray();" line.

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

What is reason for that?

Upvotes: 0

Views: 513

Answers (2)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31299

List.toArray() is a method in the interface List, and the documentation does not specify what kind of array is returned by the method. However, unlike other answers suggested, the List.toArray() method cannot return an array of the generic type of the list, because the generic type of a list is not known at runtime.

Because of that, all the implementations of List that are built-in to the standard API return an Object[], and not a String[].

However, you are allowed to pass your own pre-allocated array into the method List.toArray(Object[]). If you do that, you are guaranteed to get a return value that has the same element type as the array that you passed in. If the array that you passed in has the same size as the list itself, then that array will be used (otherwise, a new array of the proper size is allocated internally)

This will fix it:

public void method1(List s) {
    String[] array = s.toArray(new String[s.size()]);  // <-- pass the array as an argument
    for (int i = 0; i < array.length; i++) {
        System.out.println(array[i]);
    }
}

Upvotes: 2

Predrag Maric
Predrag Maric

Reputation: 24433

You didn't specify the generic type for list, and you declared array as array of Strings. This should work:

public void method1(List<String> s1){
    List<String> s=s1;
    String []array = new String[s.size()];
    array = (String[])s.toArray(array); 
    for(int i=0;i<array.length;i++){
        System.out.println(array[i]);
    }
}

EDIT
Instead of List#toArray() which returns Object[], you should use List#toArray(T[] a) which returns the type passed in as a parameter.

Upvotes: 1

Related Questions