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?

ROMANIA_engineer
  • 51,252
  • 26
  • 196
  • 186
prathik
  • 129
  • 1
  • 10

4 Answers4

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()]);
Leon
  • 11,352
  • 5
  • 33
  • 55
0

Use

String[] outResult = (String[]) listString.toArray(new String[0]);
BretC
  • 4,001
  • 12
  • 21
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();
    }    


}
Touchstone
  • 5,144
  • 7
  • 38
  • 48
-1

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

Crazyjavahacking
  • 8,777
  • 2
  • 30
  • 40