-1

I want to know if it's possible to convert a Java List of Strings to an array of Strings:

I tried this:

List<String> products = new ArrayList<String>();
//some codes..
String[] arrayCategories = (String[]) products.toArray();

but it gives me an exception message:

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

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Mouad EL Fakir
  • 3,609
  • 2
  • 23
  • 37

4 Answers4

6
String[] array = products.toArray(new String[products.size()]);
RaceBase
  • 18,428
  • 47
  • 141
  • 202
3

Use

String[] arrayCategories = products.toArray(new String[products.size()]);

products.toArray() will put list values in Object[] array, and same as you cant cast object of super type to its derived type like

//B extands A
B b = new A();

you can't store or cast Object[] array to String[] array so you need to pass array of exact type that you want to be returned.

Additional info here.

Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

Try

List<String> products = new ArrayList<String>();
        String[] arrayCategories = products.toArray(new String[products.size()]);
newuser
  • 8,338
  • 2
  • 25
  • 33
0

This should do the trick. You got an typo in the first line.

List<String> products = new ArrayList<>();
String[] array = (String[]) products.toArray();