How do I cast a Character array into a char array?

I have a List of Characters. I need to convert it into a char array. I tried this

char[] codeArray = (char[]) (Character[]) codeList.toArray(); 
/* I have to cast it to Character[] first because toArray() returns 
an array of Objects, not an array of Characters for some reason

but it didn’t work. IntelliJ IDEA says

Inconvertible types; cannot cast ‘java.lang.Character’ to ‘char

Do you think you can help me with this? Bonus question: why can’t Java cast a Character array into a char array but can cast a Character into an int? It seems weird to me, to be honest

You can’t do casting an array to another array in Java (at this point).
I don’t know of a way to convert to an array of a primitive type I think you have to convert each Character in the list or array to a char individually.
You can use a loop to do that.

Here’s a function for some of that.

  public static char[] asArray(List<Character> list) {
    int length = list.size();
    char[] array = new char[length];
    int i = 0;
    for (Character object : list) {
      array[i] = object.charValue(); //.charValue() is not necessary ('cuz of autoboxing)
    return array;
1 Like

Thanks, but you have to admit it’s vexing. Java makers could’ve easily designed the issue out