Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

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

I'd like to be able to pass cool an ArrayList<String>

Thanks

EDIT: I have tried the 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.

like image 605
Stephen D Avatar asked Dec 11 '22 11:12

Stephen D


1 Answers

Try this:

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

The above is the type-safe way to convert an ArrayList into an array, it's not a really cast, just a conversion.

Regarding the new error reported - you have to declare a no-arg constructor in the entity mentioned in the error.

like image 174
Óscar López Avatar answered Jan 07 '23 10:01

Óscar López