简体   繁体   English

Java集合:将队列实现为LinkedList吗?

[英]Java Collections: Implementation of a Queue as a linkedList?

In the following statement: 在以下语句中:

Queue<Integer> queue1= new LinkedList<Integer>();

Does this mean that queue1 will be a Queue that acts an a linkedList or a linkedList that acts as a Queue? 这是否意味着queue1将成为充当链表的队列或充当队列的链表?

Im not sure of collections, especially when they are declared as this is. 我不确定集合,尤其是当它们按原样声明时。

Queue is an interface not a class. Queue是接口而不是类。 LinkedList is an implementation of Queue interface. LinkedListQueue接口的实现。

You can think it like this. 您可以这样认为。

Animal a = new Cat()
Animal b = new Dog()
Animal c = new Cow()

a,b and c are all animals. a,b和c都是动物。 But they are all different kind of animals. 但是它们都是不同种类的动物。

There are other implementation of Queue interface like ArrayBlockingQueue and PriorityQueue. 队列接口还有其他实现,例如ArrayBlockingQueue和PriorityQueue。 They all implement Queue interface but do things diffferently inside. 它们都实现了Queue接口,但内部执行不同的操作。 http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html

You can think it like this. 您可以这样认为。 Animal a = new Cat() Animal b = new Dog() Animal c = new Cow() 动物a =新的Cat()动物b =新的Dog()动物c =新的Cow()

Parent name = new Child();

this refers to 这是指

name is a Child, but we can use the Parent reference polymorphically. name是Child,但是我们可以多态使用Parent引用。

Here in your example Queue is a interface and LinkedList is child class of Queue. 在您的示例中,这里的Queue是一个接口,而LinkedList是Queue的子类。 This is a good programming practice. 这是一个好的编程习惯。 ( Program to an interface, not an implementation ) 编程到接口,而不是实现

queue1 a LinkedList that acts as a Queue . queue1一个充当QueueLinkedList

queue1 is a LinkedList . queue1是一个LinkedList That's the constructor that was called, after all. 毕竟那是被调用的构造函数。 The LinkedList class also implements List and Deque , but since you have declared it to be a Queue , the methods provided for by that interface will be the only ones available to you without a cast, so it will generally act as a Queue . LinkedList类还实现了ListDeque ,但是由于您已将其声明为Queue ,因此该接口提供的方法将是您唯一无需强制转换即可使用的方法,因此通常将其用作Queue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM