Collection-1-2
Collection-1-2
Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
collection.
E> c)
collection.
E> filter)
collection.
the collection.
contains(Object element)
10 public boolean It is used to search the specified collection in
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the
specified array.
element)
collection.
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction
only.
There are only three methods in the Iterator interface. They are:
N Method Description
o.
1 public boolean It returns true if the iterator has more elements otherwise
2 public Object next() It returns the element and moves the cursor pointer to the
next element.
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll (
Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.
package com.flm;
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
ArrayList<String> list = new ArrayList<String>();// Creating arraylist
list.add("Ravi");// Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but
there is no size limit. We can add or remove elements anytime. So, it is much more flexible
than the traditional array. It is found in the java.util package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements the List interface
so we can use all the methods of the List interface here. The ArrayList maintains the
insertion order internally.
○ In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a
lot of shifting needs to occur if any element is removed from the array list.
○ We can not create an array list of the primitive types, such as int, float, char, etc. It is
required to use the required wrapper class in such cases. For example:
○ Java ArrayList gets initialized by the size. The size is dynamic in the array list, which
varies according to the elements getting added or removed from the list
Constructors of ArrayList
onstructor Description
ayList(Collection<? extends E> c) It is used to build an array list that is initialized with the elements of the
collection c.
ayList(int capacity) It is used to build an array list that has the specified initial capacity.
Methods of ArrayList
Method Description
void add(int index, E It is used to insert the specified element at the specified
boolean add(E e) It is used to append the specified element at the end of a list.
addAll(Collection<? collection to the end of this list, in the order that they are
extends E> c)
void clear() It is used to remove all of the elements from this list.
void It is used to enhance the capacity of an ArrayList instance.
ensureCapacity(int
requiredCapacity)
E get(int index) It is used to fetch the element from the particular position of
the list.
Iterator()
listIterator()
int It is used to return the index in this list of the last occurrence
lastIndexOf(Object of the specified element, or -1 if the list does not contain this
o) element.
contains(Object o)
int indexOf(Object o) It is used to return the index in this list of the first occurrence
element.
remove(Object o) element.
boolean It is used to remove all the elements from the list.
removeAll(Collection
<?> c)
boolean It is used to remove all the elements from the list that satisfies
protected void It is used to remove all the elements lies within the given
removeRange(int range.
fromIndex, int
toIndex)
void It is used to replace all the elements from the list with the
rator<E> operator)
void It is used to retain all the elements in the list that are present
?> c)
E set(int index, E It is used to replace the specified element in the list, present at
void It is used to sort the elements of the list on the basis of the
super E> c)
spliterator()
List<E> subList(int It is used to fetch all the elements that lies within the given
toIndex)
int size() It is used to return the number of elements present in the list.
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in a collection. Now it
is type-safe, so typecasting is not required at runtime.
In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have
the only specified type of object in it. If you try to add another type of object, it gives a
compile-time error.
import java.util.*;
list.add("Apple");
list.add("Banana");
list.add("Grapes");
import java.util.*;
list.add("Apple");
list.add("Banana");
list.add("Grapes");
FileName: ArrayListExample3.java
import java.util.*;
list.add("Apple");
list.add("Banana");
list.add("Grapes");
for(String fruit:list)
System.out.println(fruit);
The java.util package provides a utility class Collections, which has the static method sort().
Using the Collections.sort() method, we can easily sort the ArrayList.
import java.util.*;
class SortArrayList{
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
Collections.sort(list1);
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
//Creating a list of numbers
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
Collections.sort(list2);
for(Integer number:list2)
System.out.println(number);
1. By Iterator interface.
2. By for-each loop.
3. By ListIterator interface.
4. By for loop.
class Student{
int rollno;
String name;
int age;
this.rollno=rollno;
this.name=name;
this.age=age;
—--------
import java.util.*;
class ArrayList5{
al.add(s2);
al.add(s3);
//Getting Iterator
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
Size and capacity of an array list are the two terms that beginners find confusing. Let's
understand it in this section with the help of some examples. Consider the following code
snippet.
FileName: SizeCapacity.java
import java.util.*;
Output:
Explanation: The output makes sense as we have not done anything with the array list. Now
observe the following program.
import java.util.*;
Output:
Explanation: We see that the size is still 0, and the reason behind this is the number 10
represents the capacity not the size. In fact, the size represents the total number of
elements present in the array. As we have not added any element, therefore, the size of the
array list is zero in both programs.
Capacity represents the total number of elements the array list can contain. Therefore, the
capacity of an array list is always greater than or equal to the size of the array list. When we
add an element to the array list, it checks whether the size of the array list has become equal
to the capacity or not. If yes, then the capacity of the array list increases. So, in the above
example, the capacity will be 10 till 10 elements are added to the list. When we add the 11th
element, the capacity increases. Note that in both examples, the capacity of the array list is
10. In the first case, the capacity is 10 because the default capacity of the array list is 10. In
the second case, we have explicitly mentioned that the capacity of the array list is 10.
LinkedList class
Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class and implements List and Deque interfaces.
As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class
and implements List and Deque interfaces.
In the case of a doubly linked list, we can add or remove elements from both sides.
Constructor Description
tion<? extends specified collection, in the order, they are returned by the
Method Description
boolean add(E e) It is used to append the specified element to the end of a list.
void add(int index, It is used to insert the specified element at the specified
addAll(Collection<? collection to the end of this list, in the order that they are
addAll(Collection<? collection to the end of this list, in the order that they are
boolean addAll(int It is used to append all the elements in the specified collection,
extends E> c)
void addFirst(E e) It is used to insert the given element at the beginning of a list.
void addLast(E e) It is used to append the given element to the end of a list.
contains(Object o)
E get(int index) It is used to return the element at the specified position in a list.
E getFirst() It is used to return the first element in a list.
int indexOf(Object It is used to return the index in a list of the first occurrence of
element.
lastIndexOf(Object the specified element, or -1 if the list does not contain any
o) element.
index)
boolean offer(E e) It adds the specified element as the last element of a list.
boolean offerFirst(E It inserts the specified element at the front of a list.
e)
e)
empty.
empty.
if a list is empty.
list.
removeFirstOccurre element in a list (when traversing the list from head to tail).
nce(Object o)
nce(Object o)
E set(int index, E It replaces the element at the specified position in a list with
Object[] toArray() It is used to return an array containing all the elements in a list
<T> T[] toArray(T[] It returns an array containing all the elements in the proper
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
However, there are many differences between the ArrayList and LinkedList classes that are
given below.
ArrayList LinkedList
because it internally uses an array. If any faster than ArrayList because it uses
element is removed from the array, all the a doubly linked list, so no bit shifting
3) An ArrayList class can act as a list only LinkedList class can act as a list and
5) The memory location for the elements of The location for the elements of a
LinkedList is initialized.
Points to Remember
The following are some important points to remember regarding an ArrayList and
LinkedList.
○ When the rate of addition or removal rate is more than the read scenarios, then go for
the LinkedList. On the other hand, when the frequency of the read scenarios is more
than the addition or removal rate, then ArrayList takes precedence over LinkedList.
Method Description
void add(E e) This method inserts the specified element into the list.
boolean This method returns true if the list iterator has more elements while
E next() This method returns the next element in the list and advances the
cursor position.
int This method returns the index of the element that would be returned
boolean This method returns true if this list iterator has more elements while
E previous() This method returns the previous element in the list and moves the
E This method returns the index of the element that would be returned
x()
void This method removes the last element from the list that was returned
void set(E e) This method replaces the last element returned by next() or previous()
al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");
ListIterator<String> itr=al.listIterator();
while(itr.hasNext()){
System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
while(itr.hasPrevious()){
System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
}
Java HashSet
Java HashSet class is used to create a collection that uses a hash table for storage. It
inherits the AbstractSet class and implements Set interface.
○ HashSet doesn't maintain the insertion order. Here, elements are inserted on the
basis of their hashcode.
A list can contain duplicate elements whereas Set contains unique elements only.
2) void clear() It is used to remove all of the elements from the set.
3) object clone() It is used to return a shallow copy of this HashSet
4) boolea contains( It is used to return true if this set contains the specified
n Object o) element.
r<E> set.
7) boolea remove(O It is used to remove the specified element from this set if
n bject o) it is present.
Let's see a simple example of HashSet. Notice, the elements iterate in an unordered
collection.
import java.util.*;
class HashSet1{
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
System.out.println(i.next());
}
Java LinkedHashSet Class
Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set
interface. It inherits the HashSet class and implements the Set interface.
○ Java LinkedHashSet class provides all optional set operations and permits null
elements.
The LinkedHashSet class extends the HashSet class, which implements the Set interface.
The Set interface inherits Collection and Iterable interfaces in hierarchical order.
Constructor Description
HashSet(Collection c) It is used to initialize the hash set by using the elements of the
collection c.
LinkedHashSet(int It is used to initialize the capacity of the linked hash set to the
LinkedHashSet(int It is used to initialize both the capacity and the fill ratio (also
capacity, float fillRatio) called load capacity) of the hash set from its argument.
Let's see a simple example of the Java LinkedHashSet class. Here you can notice that the
elements iterate in insertion order.
FileName: LinkedHashSet1.java
import java.util.*;
class LinkedHashSet1{
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
System.out.println(i.next());
TreeSet class
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet
class are stored in ascending order.
○ Java TreeSet class access and retrieval times are quiet fast.
○ The TreeSet can only allow those generic types that are comparable. For example The
Comparable interface is being implemented by the StringBuffer class.
As already mentioned above, the TreeSet class is not synchronized. It means if more than
one thread concurrently accesses a tree set, and one of the accessing threads modify it,
then the synchronization must be done manually. It is usually done by doing some object
synchronization that encapsulates the set. However, in the case where no such object is
found, then the set must be wrapped with the help of the Collections.synchronizedSet()
method. It is advised to use the method during creation time in order to avoid the
unsynchronized access of the set. The following code snippet shows the same.
Constructor Description
TreeSet(Collection<? It is used to build a new tree set that contains the elements of
s) given SortedSet.
Methods of Java TreeSet Class
Method Description
in order.
order.
is no such element.
SortedSet headSet(E toElement) It returns the group of elements that are less
NavigableSet headSet(E toElement, It returns the group of elements that are less
element.
such element.
order.
such element.
E pollFirst() It is used to retrieve and remove the lowest(first)
element.
element.
NavigableSet subSet(E fromElement, It returns a set of elements that lie between the
boolean toInclusive)
SortedSet subSet(E fromElement, E It returns a set of elements that lie between the
excludes toElement.
SortedSet tailSet(E fromElement) It returns a set of elements that are greater than
element.
element.
set.
instance.
FileName: TreeSet1.java
import java.util.*;
class TreeSet1{
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
—-----
import java.util.*;
class TreeSet3{
set.add(24);
set.add(66);
set.add(12);
set.add(15);
}
Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store
n-number of elements in it as there is no size limit. It is a part of Java Collection framework
since Java 1.2. It is found in the java.util package and implements the List interface, so we
can use all the methods of List interface here.
It is recommended to use the Vector class in the thread-safe implementation only. If you
don't need to use the thread-safe implementation, you should use the ArrayList, the ArrayList
will perform better in such case.
Vector class supports four types of constructors. These are given below:
S Constructor Description
N
S Method Description
N
8) containsAll() It returns true if the vector contains all of the elements in the
specified collection.
9) copyInto() It is used to copy the components of the vector into the specified
array.
0)
1)
2) ity() necessary. It ensures that the vector can hold at least the number of
1 equals() It is used to compare the specified object with the vector for equality.
3)
1 firstElement() It is used to get the first component of the vector.
4)
1 forEach() It is used to perform the given action for each element of the Iterable
exception.
6)
7)
1 indexOf() It is used to get the index of the first occurrence of the specified
8) element in the vector. It returns -1 if the vector does not contain the
element.
0)
2 iterator() It is used to get an iterator over the elements in the list in proper
1) sequence.
2)
2 lastIndexOf() It is used to get the index of the last occurrence of the specified
3) element in the vector. It returns -1 if the vector does not contain the
element.
2 listIterator() It is used to get a list iterator over the elements in the list in proper
4) sequence.
2 remove() It is used to remove the specified element from the vector. If the
2 removeAll() It is used to delete all the elements from the vector that are present in
2 removeAllEle It is used to remove all elements from the vector and set the size of
9) ntAt()
3 removeIf() It is used to remove all of the elements of the collection that satisfy
3 removeRang It is used to delete all of the elements from the vector whose index is
3 replaceAll() It is used to replace each element of the list with the result of
3 retainAll() It is used to retain only that element in the vector which is contained
3 set() It is used to replace the element at the specified position in the vector
6)
7)
3 sort() It is used to sort the list according to the order induced by the
8) specified Comparator.
4 subList() It is used to get a view of the portion of the list between fromIndex,
4 toArray() It is used to get an array containing all of the elements in this vector
1) in correct order.
4 toString() It is used to get a string representation of the vector.
2)
4 trimToSize() It is used to trim the capacity of the vector to the vector's current size.
3)
//Create a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
Java Stack
The stack is a linear data structure that is used to store the collection of objects. It is based
on Last-In-First-Out (LIFO). Java collection framework provides many interfaces and
classes to store the collection of objects. One of them is the Stack class that provides
different operations such as push, pop, search, etc.
In this section, we will discuss the Java Stack class, its methods, and implement the stack
data structure in a Java program. But before moving to the Java Stack class have a quick
view of how the stack works.
The stack data structure has the two most important operations that are push and pop. The
push operation inserts an element into the stack and pop operation removes an element
from the top of the stack. Let's see how they work on stack.
Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.
○ Push 6, top=1
○ Push 9, top=2
When we pop an element from the stack the value of top is decreased by 1. In the following
figure, we have popped 9.
The following table shows the different values of the top.
1. public Stack()
Creating a Stack
If we want to create a stack, first, import the java.util package and create an object of the
Stack class.
Where type denotes the type of stack like Integer, String, etc.
push(E E The method pushes (insert) an element onto the top of the stack.
item)
pop() E The method removes an element from the top of the stack and
peek() E The method looks at the top element of the stack without
removing it.
search(O int The method searches the specified object and returns the
The empty() method of the Stack class check the stack is empty or not. If the stack is
empty, it returns true, else returns false. We can also use the isEmpty() method of the Vector
class.
Syntax
Returns: The method returns true if the stack is empty, else returns false.
In the following example, we have created an instance of the Stack class. After that, we have
invoked the empty() method two times. The first time it returns true because we have not
pushed any element into the stack. After that, we have pushed elements into the stack.
Again we have invoked the empty() method that returns false because the stack is not
empty.
StackEmptyMethodExample.java
1. import java.util.Stack;
2. public class StackEmptyMethodExample
3. {
4. public static void main(String[] args)
5. {
6. //creating an instance of Stack class
7. Stack<Integer> stk= new Stack<>();
8. // checking stack is empty or not
9. boolean result = stk.empty();
10. System.out.println("Is the stack empty? " + result);
11. // pushing elements into stack
12. stk.push(78);
13. stk.push(113);
14. stk.push(90);
15. stk.push(120);
16. //prints elements of the stack
17. System.out.println("Elements in Stack: " + stk);
18. result = stk.empty();
19. System.out.println("Is the stack empty? " + result);
20. }
21. }
Output:
The method inserts an item onto the top of the stack. It works the same as the method
addElement(item) method of the Vector class. It passes a parameter item to be pushed into
the stack.
Syntax
Returns: The method returns the argument that we have passed as a parameter.
The method removes an object at the top of the stack and returns the same object. It throws
EmptyStackException if the stack is empty.
Syntax
1. public E pop()
Let's implement the stack in a Java program and perform push and pop operations.
StackPushPopExample.java
1. import java.util.*;
2. public class StackPushPopExample
3. {
4. public static void main(String args[])
5. {
6. //creating an object of Stack class
7. Stack <Integer> stk = new Stack<>();
8. System.out.println("stack: " + stk);
9. //pushing elements into the stack
10. pushelmnt(stk, 20);
11. pushelmnt(stk, 13);
12. pushelmnt(stk, 89);
13. pushelmnt(stk, 90);
14. pushelmnt(stk, 11);
15. pushelmnt(stk, 45);
16. pushelmnt(stk, 18);
17. //popping elements from the stack
18. popelmnt(stk);
19. popelmnt(stk);
20. //throws exception if the stack is empty
21. try
22. {
23. popelmnt(stk);
24. }
25. catch (EmptyStackException e)
26. {
27. System.out.println("empty stack");
28. }
29. }
30. //performing push operation
31. static void pushelmnt(Stack stk, int x)
32. {
33. //invoking push() method
34. stk.push(new Integer(x));
35. System.out.println("push -> " + x);
36. //prints modified stack
37. System.out.println("stack: " + stk);
38. }
39. //performing pop operation
40. static void popelmnt(Stack stk)
41. {
42. System.out.print("pop -> ");
43. //invoking pop() method
44. Integer x = (Integer) stk.pop();
45. System.out.println(x);
46. //prints modified stack
47. System.out.println("stack: " + stk);
48. }
49. }
Output:
stack: []
push -> 20
stack: [20]
push -> 13
push -> 89
push -> 90
push -> 11
push -> 45
push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]
pop -> 18
pop -> 45
pop -> 11
It looks at the element that is at the top in the stack. It also throws EmptyStackException if
the stack is empty.
Syntax
1. public E peek()
StackPeekMethodExample.java
1. import java.util.Stack;
2. public class StackPeekMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. // pushing elements into Stack
8. stk.push("Apple");
9. stk.push("Grapes");
10. stk.push("Mango");
11. stk.push("Orange");
12. System.out.println("Stack: " + stk);
13. // Access element from the top of the stack
14. String fruits = stk.peek();
15. //prints stack
16. System.out.println("Element at top: " + fruits);
17. }
18. }
Output:
The method searches the object in the stack from the top. It parses a parameter that we
want to search for. It returns the 1-based location of the object in the stack. Thes topmost
object of the stack is considered at distance 1.
Suppose, o is an object in the stack that we want to search for. The method returns the
distance from the top of the stack of the occurrence nearest the top of the stack. It uses
equals() method to search an object in the stack.
Syntax
Returns: It returns the object location from the top of the stack. If it returns -1, it means that
the object is not on the stack.
StackSearchMethodExample.java
1. import java.util.Stack;
2. public class StackSearchMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. //pushing elements into Stack
8. stk.push("Mac Book");
9. stk.push("HP");
10. stk.push("DELL");
11. stk.push("Asus");
12. System.out.println("Stack: " + stk);
13. // Search an element
14. int location = stk.search("HP");
15. System.out.println("Location of Dell: " + location);
16. }
17. }
Java Stack Operations
We can also find the size of the stack using the size() method of the Vector class. It returns
the total number of elements (size of the stack) in the stack.
Syntax
StackSizeExample.java
1. import java.util.Stack;
2. public class StackSizeExample
3. {
4. public static void main (String[] args)
5. {
6. Stack stk = new Stack();
7. stk.push(22);
8. stk.push(33);
9. stk.push(44);
10. stk.push(55);
11. stk.push(66);
12. // Checks the Stack is empty or not
13. boolean rslt=stk.empty();
14. System.out.println("Is the stack empty or not? " +rslt);
15. // Find the size of the Stack
16. int x=stk.size();
17. System.out.println("The stack size is: "+x);
18. }
19. }
Output:
Iterate Elements
Iterate means to fetch the elements of the stack. We can fetch elements of the stack using
three different methods are as follows:
It is the method of the Iterator interface. It returns an iterator over the elements in the stack.
Before using the iterator() method import the java.util.Iterator package.
Syntax
1. Iterator<T> iterator()
StackIterationExample1.java
1. import java.util.Iterator;
import java.util.Stack;
stk.push("BMW");
stk.push("Audi");
stk.push("Ferrari");
stk.push("Bugatti");
stk.push("Jaguar");
while(iterator.hasNext())
System.out.println(values);
}
2. }
Output:
BMW
Audi
Ferrari
Bugatti
Jaguar
Java provides a forEach() method to iterate over the elements. The method is defined in the
Iterable and Stream interface.
Syntax
StackIterationExample2.java
import java.util.*;
stk.push(119);
stk.push(203);
stk.push(988);
stk.forEach(n ->
System.out.println(n);
});
Output:
203
988
This method returns a list iterator over the elements in the mentioned list (in sequence),
starting at the specified position in the list. It iterates the stack from top to bottom.
Syntax
Returns: This method returns a list iterator over the elements, in sequence.
StackIterationExample3.java
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Stack;
stk.push(119);
stk.push(203);
stk.push(988);
while (ListIterator.hasPrevious())
System.out.println(avg);
Metho Description
d
boolean It is used to insert the specified element into this deque and return true upon
add(obje success.
ct)
offer(obj
ect)
Object It is used to retrieve and removes the head of this deque.
remove(
Object It is used to retrieve and removes the head of this deque, or returns null if this
Object It is used to retrieve, but does not remove, the head of this deque.
element(
Object It is used to retrieve, but does not remove, the head of this deque, or returns
Object The method returns the head element of the deque. The method does not
peekFirs remove any element from the deque. Null is returned by this method, when the
Object The method returns the last element of the deque. The method does not
peekLas remove any element from the deque. Null is returned by this method, when the
t(e)
Object Inserts the element e at the tail of the queue. If the insertion is successful, true
t(e)
ArrayDeque class
We know that it is not possible to create an object of an interface in Java. Therefore, for
instantiation, we need a class that implements the Deque interface, and that class is
ArrayDeque. It grows and shrinks as per usage. It also inherits the AbstractCollection class.
ArrayDeque Hierarchy
The hierarchy of ArrayDeque class is given in the figure displayed at the right side of the
page.
FileName: ArrayDequeExample.java
import java.util.*;
deque.add("Ravi");
deque.add("Vijay");
deque.add("Ajay");
//Traversing elements
System.out.println(str);
Output:
Ravi
Vijay
Ajay
FileName: DequeExample.java
import java.util.*;
deque.offer("arvind");
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
for(String s:deque){
System.out.println(s);
//deque.poll();
deque.pollLast();
for(String s:deque){
System.out.println(s);
}
}
Output:
jai
arvind
vimal
mukul
jai
arvind
vimal
FileName: ArrayDequeExample.java
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
//Creating Books
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing ArrayDeque
for(Book b:set){