Search code examples
javaqueue

How to enqueue and dequeue without using add() and remove()?


My attempt so far

import java.util.Queue;
import java.util.LinkedList;
public class QueueQuiz {
    public static void main (String [] args){
        Queue beverages = new LinkedList();
        beverages.offer("shoes");
        beverages.offer("ball"); //enqueue ball without using add()
        System.out.println(beverages.peek() + " is queued first.");
        beverages.poll(); //dequeue ball without using remove()
        System.out.println("Element(s) in the queue: " + beverages);
    }
}

I already dequeue the "ball", but it pops when I call the element in the queue not "shoes". How could I fix it?


Solution

  • How to enqueue without using add

    By using .offer().

    How to dequeue without using remove

    By using .poll().

    In other words, you're doing it.

    I dequeue already the "ball" but it pops when I call the element in the queue not "shoes"

    Of course. You put your shoes in the drawer. Then, you put the ball in the drawer, which moves the shoes to the back of the cupboard. Then, you open the drawer and take the first thing your hands can touch back out, which is the ball.

    The drawer now contains just the shoes.