How to define a char stack?

Using a collection of char is pretty inefficient. (but it works) You could wrap a StringBuilder which is also a mutable collection of char.

class CharStack {
    final StringBuilder sb = new StringBuilder();

    public void push(char ch) {
        sb.append(ch);
    }

    public char pop() {
        int last = sb.length() -1;
        char ch= sb.charAt(last);
        sb.setLength(last);
        return ch;
    }

    public int size() {
        return sb.length();
    }
}

Primitive types such as char cannot be used as type parameters in Java. You need to use the wrapper type:

Stack<Character> stack = new Stack<Character>();

char is one of the primitive datatypes in Java, which cannot be used in generics. You can, however, substitute the wrapper java.lang.Character, as in:

Stack<Character> stack = new Stack<Character>();

You can assign a Character to a char or the other way around; Java will autobox the value for you.

Tags:

Java