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
  • 54,432
  • 29
  • 203
  • 199
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
  • 12,013
  • 5
  • 36
  • 59
0

Use

String[] outResult = (String[]) listString.toArray(new String[0]);
BretC
  • 4,141
  • 13
  • 22
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,575
  • 7
  • 41
  • 48
-1

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

Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40