Dmitry Zaytsev
Dmitry Zaytsev

Reputation: 23962

How to define a char stack?

How to define a char stack in java? For example, to create a String stack I can use such construction:

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

But when I'm try to put char instead String I got an error:

Syntax error on token "char", Dimensions expected after this token

Upvotes: 19

Views: 76312

Answers (4)

phihag
phihag

Reputation: 287835

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.

Upvotes: 14

Sarvesh Mishra
Sarvesh Mishra

Reputation: 11

char[] stack=new char[s.length()]

where s is the string passed as function argument.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533500

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();
    }
}

Upvotes: 7

Tudor
Tudor

Reputation: 62439

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>();

Upvotes: 68

Related Questions