Join Regular Classroom : Visit ClassroomTech

JAVA – codewindow.in

Related Topics

JAVA Programming

Deque<Integer> deque = new LinkedList<>();
deque.addFirst(1);
deque.addLast(2);
deque.addLast(3);

The order of the elements in the deque will be 1, 2, 3.

We can also remove elements from both ends of the deque:

int first = deque.removeFirst(); // returns 1
int last = deque.removeLast(); // returns 3

After this, the order of the elements in the deque will be 2.

Overall, Deque is a useful interface in Java for working with sequences of elements that can be accessed and modified at both ends, and provides a versatile and efficient way to implement various data structures such as queues, stacks, and more.

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);

We can also create a Vector of integers and add some elements to it:

List<Integer> vector = new Vector<>();
vector.add(1);
vector.add(2);
vector.add(3);

Both lists will contain the same elements in the same order, but the Vector will have the additional overhead of synchronization.

Vector<String> vector = new Vector<>();
vector.add("foo");
vector.add("bar");
vector.add("baz");

Enumeration<String> e = vector.elements();
while (e.hasMoreElements()) {
    String element = e.nextElement();
    System.out.println(element);
}

This will print out the elements “foo”, “bar”, and “baz” on separate lines.

Although the Enumeration interface is still supported in Java, it is recommended to use the Iterator interface instead, which has several advantages such as better support for removing elements from a collection while iterating, and more consistent behavior across different collection classes. Therefore, the Enumeration interface is mainly used with older APIs that have not yet been updated to use the Iterator interface.

BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);

// Producer thread
new Thread(() -> {
    while (true) {
        try {
            queue.put("data"); // blocks if queue is full
        } catch (InterruptedException e) {
            // handle interruption
        }
    }
}).start();

// Consumer thread
new Thread(() -> {
    while (true) {
        try {
            String data = queue.take(); // blocks if queue is empty
            // process data
        } catch (InterruptedException e) {
            // handle interruption
        }
    }
}).start();

In this example, the producer thread adds elements to the queue using the put() method, which will block if the queue is full, and the consumer thread removes elements from the queue using the take() method, which will block if the queue is empty. This ensures that the producer and consumer threads are properly coordinated and do not overwrite or read invalid data from the queue.

      

Go through our study material. Your Job is awaiting.

Recent Posts
Categories