Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a char stack?

Tags:

java

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
like image 902
Dmitry Zaytsev Avatar asked Jan 05 '12 16:01

Dmitry Zaytsev


People also ask

How do you declare a character stack in C++?

To use stack in C++ we have to include teh header file #include <stack> and then we can define stack of any type using the format stack <TYPE> name; for example : stack <int> s1; will create an integer stack s1 . stack <char> s2; will create a character stack s2 .

Can we store char in stack?

Stack<Character> myStack = new Stack<Character>(); char letter = 'a'; myStack. push((Character) letter); Create a stack that contains Character objects, and cast your char s to Character before you insert them. Just like int s and Integer s, you need to wrap a primitive before you can insert it in to a data structure.

How do you define a char in Java?

The char keyword is a data type that is used to store a single character. A char value must be surrounded by single quotes, like 'A' or 'c'.


2 Answers

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>();
like image 175
Tudor Avatar answered Oct 28 '22 14:10

Tudor


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.

like image 21
phihag Avatar answered Oct 28 '22 15:10

phihag