ArrayDeque class of chars
I'm trying to move a paren balancer I wrote in C++ to Java.
I'm trying to implement the stack with an ArrayDeque class from the Deque interface by declaring an ArrayDeque of characters like so:
Deque<char> parens = new ArrayDeque<char>();
and the compiler chokes on it开发者_运维百科 claiming
expected: reference
found: char
What am I missing?
You can't use primitive types as generic parameters. You need the corresponding Object wrappers:
Deque<Character> parens = new ArrayDeque<Character>();
Let's update our Box class to use generics. We'll first create a generic type declaration by changing the code
public class Box
topublic class Box<T>
; this introduces one type variable, namedT
, that can be used anywhere inside the class. This same technique can be applied to interfaces as well. There's nothing particularly complex about this concept. In fact, it's quite similar to what you already know about variables in general. Just think ofT
as a special kind of variable, whose "value" will be whatever type you pass in; this can be any class type, any interface type, or even another type variable. It just can't be any of the primitive data types. In this context, we also say thatT
is a formal type parameter of the Box class.[Source: Java Tutorial : Generics : Generic Types]
See:
- Java Tutorial: Generics
- JLS: 4.4 Type Variables
- JLS: 4.5 Parameterized Types
You need to use ArrayDeque<Character>
in Java.
精彩评论