问题描述
当我尝试时:
Queue<Integer> q = new Queue<Integer>();
编译器给了我一个错误.有什么帮助吗?
The compiler is giving me an error. Any help?
另外,如果我想初始化一个队列,我必须实现队列的方法吗?
Also, if I want to initialize a queue do I have to implement the methods of the queue?
推荐答案
Queue
是接口,不能直接构造Queue
.
A Queue
is an interface, which means you cannot construct a Queue
directly.
最好的选择是构建一个已经实现 Queue
接口的类,例如以下之一:AbstractQueue
、ArrayBlockingQueue
、ArrayDeque
、ConcurrentLinkedQueue
、DelayQueue
、LinkedBlockingQueue
、LinkedList
、PriorityBlockingQueue
、PriorityQueue
或 SynchronousQueue
.
The best option is to construct off a class that already implements the Queue
interface, like one of the following: AbstractQueue
, ArrayBlockingQueue
, ArrayDeque
, ConcurrentLinkedQueue
, DelayQueue
, LinkedBlockingQueue
, LinkedList
, PriorityBlockingQueue
, PriorityQueue
, or SynchronousQueue
.
另一种方法是编写自己的类来实现必要的 Queue 接口.除非在极少数情况下您希望在为程序的其余部分提供 Queue
的同时做一些特别的事情,否则不需要它.
An alternative is to write your own class which implements the necessary Queue interface. It is not needed except in those rare cases where you wish to do something special while providing the rest of your program with a Queue
.
public class MyQueue<T extends Tree> implements Queue<T> {
public T element() {
... your code to return an element goes here ...
}
public boolean offer(T element) {
... your code to accept a submission offer goes here ...
}
... etc ...
}
一个更少使用的替代方法是构造一个实现 Queue
的匿名类.您可能不想这样做,但为了涵盖所有基础,它被列为一个选项.
An even less used alternative is to construct an anonymous class that implements Queue
. You probably don't want to do this, but it's listed as an option for the sake of covering all the bases.
new Queue<Tree>() {
public Tree element() {
...
};
public boolean offer(Tree element) {
...
};
...
};
这篇关于如何在 java 中实例化 Queue 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!