How do I instantiate a Queue object in java?

WM. picture WM. · Jan 7, 2011 · Viewed 325k times · Source

When I try:

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?

Answer

Jon Skeet picture Jon Skeet · Jan 7, 2011

Queue is an interface. You can't instantiate an interface directly except via an anonymous inner class. Typically this isn't what you want to do for a collection. Instead, choose an existing implementation. For example:

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

or

Queue<Integer> q = new ArrayDeque<Integer>();

Typically you pick a collection implementation by the performance and concurrency characteristics you're interested in.