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