我正在尝试将我用 C++ 编写的双括号平衡器移动到 Java。
我试图通过像这样声明字符的 ArrayDeque 来使用 Deque 接口(interface)中的 ArrayDeque 类来实现堆栈:
Deque<char> parens = new ArrayDeque<char>();
编译器在声明中窒息
expected: reference<br/>
found: char
我错过了什么?
最佳答案
您不能将原始类型用作泛型参数。您需要相应的对象包装器:
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]
参见:
关于java - ArrayDeque 类的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7286200/