queue_array_list
Tue May 28 2024 15:59:41 GMT+0000 (Coordinated Universal Time)
Saved by @adsj
import java.util.ArrayList; class GenericQueue<T> { private ArrayList<T> queue; // Constructor public GenericQueue() { queue = new ArrayList<>(); } // Enqueue method to add an element to the end of the queue public void enqueue(T value) { queue.add(value); } // Dequeue method to remove and return the front element of the queue public T dequeue() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return queue.remove(0); } // Peek method to return the front element without removing it public T peek() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return queue.get(0); } // Check if the queue is empty public boolean isEmpty() { return queue.isEmpty(); } // Get the size of the queue public int size() { return queue.size(); } } public class GenericQueueDemo { public static void main(String[] args) { // Integer queue GenericQueue<Integer> intQueue = new GenericQueue<>(); intQueue.enqueue(1); intQueue.enqueue(2); intQueue.enqueue(3); System.out.println("Front of Integer queue: " + intQueue.peek()); System.out.println("Dequeue from Integer queue: " + intQueue.dequeue()); System.out.println("Size of Integer queue: " + intQueue.size()); // Double queue GenericQueue<Double> doubleQueue = new GenericQueue<>(); doubleQueue.enqueue(1.1); doubleQueue.enqueue(2.2); doubleQueue.enqueue(3.3); System.out.println("Front of Double queue: " + doubleQueue.peek()); System.out.println("Dequeue from Double queue: " + doubleQueue.dequeue()); System.out.println("Size of Double queue: " + doubleQueue.size()); // String queue GenericQueue<String> stringQueue = new GenericQueue<>(); stringQueue.enqueue("Hello"); stringQueue.enqueue("World"); System.out.println("Front of String queue: " + stringQueue.peek()); System.out.println("Dequeue from String queue: " + stringQueue.dequeue()); System.out.println("Size of String queue: " + stringQueue.size()); } }
Comments