Cast ArrayList <String> to String [] in one expression?

I have a constructor that accepts an ArrayList<String> , but wants to call super , expecting an array of String[] .

I tried the following, but this results in a class exception, [Ljava.lang.Object; cannot be cast to [Ljava.lang.String; [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

 public cool(ArrayList<String> s) { super((String[]) s.toArray()); } 

I would like to go cool a ArrayList<String>

thanks

EDIT: I tried a recent suggestion to use

 super(s.toArray(new String[s.size()])); 

but now I get the following exception:

entity must have a no-arg constructor.; nested exception is java.lang.IllegalArgumentException: : entity must have a no-arg constructor.

+4
source share
1 answer

Try the following:

 super(s.toArray(new String[s.size()])); 

The above type is a safe way to convert an ArrayList to an array, it is not really great, just a conversion.

Regarding the new error, you must declare the no-arg constructor in the entity mentioned in the error.

+13
source

Source: https://habr.com/ru/post/1501927/


All Articles