'Is there a way to convert an Object[] array to char[] array?

class Solution {
    char[] make(String s){
        Stack<Character> st= new Stack<Character>();
        for(char c:s.toCharArray()){
            if(c!='#'){
                st.push(c);
            }
            else if(!st.isEmpty()){
                st.pop();
            }
        }
        return (char [])(st.toArray());
    }
    public boolean backspaceCompare(String S, String T) {
        char[] ch1=make(S);
        char[] ch2=make(T);
        int i,j;
        if(ch1.length!=ch2.length)
            return false;
        else{
            for(i=0;i<ch1.length;i++){
                if(ch1[i]!=ch2[i]){
                    return false;
                }
            }
        }
        return true;
    }
}

the above piece of code gives an error: incompatible types: Object[] cannot be converted to char[] return (char [])(st.toArray());

i tried to typecast using Character[] but that cannot be converted to char[] apparantely

is there any mthod in java to convert an Object[] containing characters only into a character array i.e char[] so that i can return a char[] from the make function



Solution 1:[1]

Well, if you have to it's easy to program:

Character[] refArray = (Character[]) st.toArray();
char[] charArray = new char[refArray.length];
for (int i = 0; i < refArray.length; i++) {
    charArray[i] = refArray[i];
}
return charArray;

Note that a more specified collection should probably be preferred, possibly something build around a StringBuilder or something similar (if you have many characters). It's rather wasteful to use a reference per character, after all (but yeah, computers nowadays).

Solution 2:[2]

If you work with Character only you can use the toArray <T> T[] toArray(T[] a) override

Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array.

Character[] make(String s){
    Stack<Character> st = new Stack<Character>();
    //...
    return st.toArray(new Character[st.size()]);
}

public boolean backspaceCompare(String S, String T) {
    Character[] ch1 = make(S);
    Character[] ch2 = make(T);
    //...
}

Solution 3:[3]

Using the following Stream API code should work, while collecting with StringBuilder also accepts Object elements:

char[] chars = Stream.of(st.toArray())
  .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
  .toString()
  .toCharArray();

You might want to convert your source array into a Character[] array first, depending on your use case:

st.toArray(Character[]::new);

The Stream conversion via StringBuilder above should work with both source arrays.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maarten Bodewes
Solution 2 Guy
Solution 3 fozzybear