0

I just append two string array into one array list and then convert it to string array to pass return variable as string[]

public static void main(String[] args) {

    String [] a = {"america", "bakrain", "canada"};
    String [] b = {"denmark", "europe" };
    try{
        List<String> listString = new ArrayList<String>(Arrays.asList(a));
        listString.addAll(Arrays.asList(b));
        String [] outResult= (String[])listString.toArray();
        System.out.println(outResult);

    } catch (Exception e) {
        e.printStackTrace();
    }    

}

the error comes

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at myFirst.myClass.main(myClass.java:26)

How to solve this issue?

1
  • String [] outResult= new String[listString.size()]; listString.toArray(outResult); Commented Apr 15, 2015 at 11:08

4 Answers 4

3

You would need to individually cast each member in the array because the result is Object[] not String[]

Or just do

String [] outResult= listString.toArray(new String[listString.size()]);
Sign up to request clarification or add additional context in comments.

Comments

0

Try the following solution:

public static void main(String[] args) {
    // TODO Auto-generated method stub          

    String [] a = {"america", "bakrain", "canada"};
    String [] b = {"denmark", "europe" };
    try{
        List<String> listString = new ArrayList<String>(Arrays.asList(a));
        listString.addAll(Arrays.asList(b));

        System.out.println(listString);
        String [] outResult= new String[listString.size()];

        int i=0;
        for(String str: listString){
            outResult[i]=str;
            i++;
        }


    } catch (Exception e) {
        e.printStackTrace();
    }    


}

Comments

0

Use

String[] outResult = (String[]) listString.toArray(new String[0]);

Comments

-1

listString.toArray(); will return Object[], not String[]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.