Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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

thanks!

share|improve this question

marked as duplicate by Maroun Maroun, ppeterka, Lalit Poptani, Reimeus, Pshemo Sep 11 '13 at 10:48

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
@LalitPoptani The duplicate I've found is better :D – Maroun Maroun Sep 11 '13 at 10:45
    
Duplicate is Duplicate better or worse :P – Lalit Poptani Sep 11 '13 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.. – mico Sep 11 '13 at 10:52
    
hmmm. now that my edit is wrong, that is corrected. May it remain closed. – mico Sep 11 '13 at 10:56
up vote 4 down vote accepted
String[] array = products.toArray(new String[products.size()]);
share|improve this answer
    
it gaves me the same Exception – Mouad EL Fakir Sep 11 '13 at 10:47
    
@MouadELFakir, then you might be doing something else wrong. Post your code to check what you are messing up – Reddy Sep 11 '13 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 ;) – Mouad EL Fakir Sep 11 '13 at 10:51
    
@MouadELFakir, if this answer works for you, you can mark it as answer – Reddy Sep 11 '13 at 11:01

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.

share|improve this answer

Try

List<String> products = new ArrayList<String>();
        String[] arrayCategories = products.toArray(new String[products.size()]);
share|improve this answer

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

List<String> products = new ArrayList<>();
String[] array = (String[]) products.toArray();
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.