19

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
Dmitry Zaytsev
  • 23,650
  • 14
  • 92
  • 146

4 Answers4

68

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>();
Tudor
  • 61,523
  • 12
  • 102
  • 142
14

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.

Neuron
  • 5,141
  • 5
  • 38
  • 59
phihag
  • 278,196
  • 72
  • 453
  • 469
7

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();
    }
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • I'm not sure about .append() method. Is it really works faster than stack? – Dmitry Zaytsev Jan 05 '12 at 17:19
  • 2
    If you have a new Character (~ 16 bytes) and you have to add it to a Stack (4 bytes per reference) it will be much larger than just adding a char (2 bytes) Even if you have a cached character it will be twice as big. Stack is also thread safe which makes it slightly slower. You can add and remove char(s) in a StringBuilder without creating any garbage. (Unless the "stack" get longer) – Peter Lawrey Jan 05 '12 at 17:24
  • Thanks a lot ) Then I'll use your solution – Dmitry Zaytsev Jan 05 '12 at 17:28
0
char[] stack=new char[s.length()]

where s is the string passed as function argument.

Neuron
  • 5,141
  • 5
  • 38
  • 59
  • 1
    Hi Sarvesh Mishra and welcome on SO! This question has already been answered, please refrain from answering questions that have already been answered if your answer does not improve the existing. – Fabian Damken Aug 10 '21 at 07:58
  • 1
    Just a friendly tip.. Having to explain what a variable means is a strong indicator that you should have used a more expressive name ;) – Neuron Aug 10 '21 at 09:51
  • @Neuron I agree man!!Thanks for the tip:) – Sarvesh Mishra Aug 11 '21 at 03:19