如何在 java 中实例化 Queue 对象? [英] How do I instantiate a Queue object in java?

查看:26
本文介绍了如何在 java 中实例化 Queue 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试时:

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 接口的类,例如以下之一:AbstractQueueArrayBlockingQueueArrayDequeConcurrentLinkedQueueDelayQueueLinkedBlockingQueueLinkedListPriorityBlockingQueuePriorityQueueSynchronousQueue.

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 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆