//A Deque is a collection that allows us to manipulate elements from both the front and end of the collection. //The Deque interface has two types of methods for manipulating the front and back of the collection. //The following methods throw an exception when: //addFirst(), addLast() - there is no space to add an element. //removeFirst(), removeLast() - there is no element to remove. //getFirst(), getLast() - there is no element to get. //The following methods return a special value: //offerFirst(), offerLast() - false when there is no space to add an element. //pollFirst(), pollLast() - null when there is no element to remove. //peekFirst(), peekLast() - null when there is no element to get. Deque<String> stringDeque = new LinkedList<>(); stringDeque.addFirst("A"); // Front -> "A" <- end stringDeque.offerFirst("B"); // Return `true` - front -> "B", "A" <- end stringDeque.offerLast("Z"); // Returns `true` - front -> "B", "A", "Z" <- end String a = stringDeque.removeFirst() // Returns "B" - front -> "A", "Z" String b = stringDeque.pollLast() // Returns "Z" - front -> "A" <- back String c = stringDeque.removeLast() // Returns "A" - empty deque String d = stringDeque.peekFirst() // Returns null String e = stringDeque.getLast() // Throws NoSuchElementException // Assuming `stringDeque` has elements front -> "Mike", "Jack", "John" <- back Iterator<String> descItr = stringDeque.descendingIterator(); while(descItr.hasNext()) { System.out.println(descItr.next()); } // OUTPUT TERMINAL: "John", "Jack", "Mike"
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter