Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
    
@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
add comment

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.

4 Answers

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
add comment

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
add comment

Try

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

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
add comment

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