失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > queue初始化java 如何在java中实例化一个Queue对象?

queue初始化java 如何在java中实例化一个Queue对象?

时间:2024-06-22 15:59:26

相关推荐

queue初始化java 如何在java中实例化一个Queue对象?

When I try:

Queue q = new Queue();

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?

解决方案

A Queue is an interface, which means you cannot construct a Queue directly.

The best option is to construct off a class that already implements the Queue interface, like one of the following: AbstractQueue, ArrayBlockingQueue, ConcurrentLinkedQueue, DelayQueue, LinkedBlockingQueue, LinkedList, PriorityBlockingQueue, PriorityQueue, or SynchronousQueue.

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 implements Queue {

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 ...

}

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() {

public Tree element() {

...

};

public boolean offer(Tree element) {

...

};

...

};

如果觉得《queue初始化java 如何在java中实例化一个Queue对象?》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。