-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[]

4
  • @LalitPoptani The duplicate I've found is better :D Commented Sep 11, 2013 at 10:45
  • Duplicate is Duplicate better or worse :P Commented Sep 11, 2013 at 10:46
  • Problem here is not the Array conversion, but wrong use of [] on new ArrayList[String]() which should be new ArrayList<String>().. I was about to answer but you guys closed this.. Commented Sep 11, 2013 at 10:52
  • hmmm. now that my edit is wrong, that is corrected. May it remain closed. Commented Sep 11, 2013 at 10:56

4 Answers 4

6
String[] array = products.toArray(new String[products.size()]);
3
  • it gaves me the same Exception Commented Sep 11, 2013 at 10:47
  • @MouadELFakir, then you might be doing something else wrong. Post your code to check what you are messing up Commented Sep 11, 2013 at 10:48
  • yeah thanks i just figured out what i was missig, i just forget to fill my products list i let it empty, it s working now just fine, thank u ;) Commented Sep 11, 2013 at 10:51
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.

0

Try

List<String> products = new ArrayList<String>();
        String[] arrayCategories = products.toArray(new String[products.size()]);
0

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

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.