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


i'm trying convert list type data collection 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 "array=(string[])s.toarray();" line.

java.lang.classcastexception: [ljava.lang.object; cannot cast [ljava.lang.string;

what reason that?

list.toarray() method in interface list, , documentation not specify kind of array returned method. however, unlike other answers suggested, list.toarray() method cannot return array of generic type of list, because generic type of list not known @ runtime.

because of that, implementations of list built-in standard api return object[], , not string[].

however, allowed pass own pre-allocated array method list.toarray(object[]). if that, guaranteed return value has same element type array passed in. if array passed in has same size list itself, array used (otherwise, new array of proper size allocated internally)

this fix it:

public void method1(list s) {     string[] array = s.toarray(new string[s.size()]);  // <-- pass array argument     (int = 0; < array.length; i++) {         system.out.println(array[i]);     } } 

Comments

Popular posts from this blog

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -