简体   繁体   中英

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?

Im not sure of collections, especially when they are declared as this is.

Queue is an interface not a class. LinkedList is an implementation of Queue interface.

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. But they are all different kind of animals.

There are other implementation of Queue interface like ArrayBlockingQueue and PriorityQueue. They all implement Queue interface but do things diffferently inside. 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()

Parent name = new Child();

this refers to

name is a Child, but we can use the Parent reference polymorphically.

Here in your example Queue is a interface and LinkedList is child class of Queue. This is a good programming practice. ( Program to an interface, not an implementation )

queue1 a LinkedList that acts as a Queue .

queue1 is a 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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