PYC
PYC

Reputation: 1

Implementing a queue in Java

I am practicing with stacks and queues and have some questions about them (mostly on queues)

How would I implement a queue in my code?

package *****;

import java.util.*;

public class stackPractice {

    /**
    * @param args
    */
    public static void main(String[] args) {
        Stack st = new Stack();
        Queue q = new Queue();

        st.push(100);
        st.push(90);
        st.push(70);

        System.out.println(st);

        //st.pop();

        System.out.println(st.pop());
        System.out.println(st);
        System.out.println(st.peek());

        //value = st.peek();
    }

}

I got Stack st to work as a stack, but Queue is giving me problems

on the 2nd Queue after new, there is a red squiggly line that says "Cannot instantiate the type Queue".

Queue q = new *Queue*();

I am not sure what that means.

---edit---

I know there is no actual code for the queue to do anything yet (enqueue, dequeue, etc...).

Upvotes: 0

Views: 761

Answers (4)

Reimeus
Reimeus

Reputation: 159774

Queue is an interface and interfaces cannot be instantiated directly. Use one of its implementations to create an instance of the interface

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

Upvotes: 0

MemLeak
MemLeak

Reputation: 4640

Queue is an interface and can not be instanciated.

You could use a LinkedList. or one of the listened:

   AbstractQueue, ArrayBlockingQueue, ConcurrentLinkedQueue, DelayQueue, LinkedBlockingQueue, LinkedList, PriorityBlockingQueue, PriorityQueue, SynchronousQueue

Upvotes: 0

Fabien Sa
Fabien Sa

Reputation: 9480

Queue is an interface so you cannot instantiate it but you need to "implement" it.

See http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html

Duplicate here: How do I instantiate a Queue object in java?

Upvotes: 0

Bill the Lizard
Bill the Lizard

Reputation: 405765

Stack is a class in Java, but Queue is an interface, so you can't instantiate it. You'll need to call the constructor of one of its implementing classes.

Upvotes: 1

Related Questions