How do I instantiate a Queue object in java?

后端 未结 8 705
南旧
南旧 2020-11-29 16:39

When I try:

Queue q = new Queue();

the compiler is giving me an error. Any help?

Also, if I want to i

相关标签:
8条回答
  • 2020-11-29 17:09

    The Queue interface extends java.util.Collection with additional insertion, extraction, and inspection operations like:

    +offer(element: E): boolean // Inserting an element

    +poll(): E // Retrieves the element and returns NULL if queue is empty

    +remove(): E // Retrieves and removes the element and throws an Exception if queue is empty

    +peek(): E // Retrieves,but does not remove, the head of this queue, returning null if this queue is empty.

    +element(): E // Retrieves, but does not remove, the head of this queue, throws an exception if te queue is empty.

    Example Code for implementing Queue:

    java.util.Queue<String> queue = new LinkedList<>();
    queue.offer("Hello");
    queue.offer("StackOverFlow");
    queue.offer("User");
    
    System.out.println(queue.peek());
    
    while (queue.size() > 0){
        System.out.println(queue.remove() + " ");
    }
    //Since Queue is empty now so this will return NULL
    System.out.println(queue.peek());
    

    Output Of the code :

    Hello
    Hello 
    StackOverFlow 
    User 
    null
    
    0 讨论(0)
  • 2020-11-29 17:19

    Queue is an interface; you can't explicitly construct a Queue. You'll have to instantiate one of its implementing classes. Something like:

    Queue linkedList = new LinkedList();
    

    Here's a link to the Java tutorial on this subject.

    0 讨论(0)
提交回复
热议问题