0% found this document useful (0 votes)
4 views

Collection-1-2

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects, including methods for adding, removing, and accessing elements. It covers specific interfaces like Collection, List, and ArrayList, highlighting their functionalities and differences, as well as the evolution from non-generic to generic collections. Additionally, it includes examples of using ArrayLists, iterating through collections, and understanding size versus capacity.

Uploaded by

dinesh 0337
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Collection-1-2

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects, including methods for adding, removing, and accessing elements. It covers specific interfaces like Collection, List, and ArrayList, highlighting their functionalities and differences, as well as the evolution from non-generic to generic collections. Additionally, it includes examples of using ArrayLists, iterating through collections, and understanding size versus capacity.

Uploaded by

dinesh 0337
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

The Collection in Java is a framework that provides an architecture to store and manipulate

the group of objects.

Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.

A Collection represents a single unit of objects, i.e., a group.

No. Method Description


1 public boolean add(E e) It is used to insert an element in this

collection.

2 public boolean It is used to insert the specified collection

addAll(Collection<? extends elements in the invoking collection.

E> c)

3 public boolean It is used to delete an element from the

remove(Object element) collection.

4 public boolean It is used to delete all the elements of the

removeAll(Collection<?> c) specified collection from the invoking

collection.

5 default boolean It is used to delete all the elements of the

removeIf(Predicate<? super collection that satisfy the specified predicate.

E> filter)

6 public boolean It is used to delete all the elements of invoking

retainAll(Collection<?> c) collection except the specified collection.

7 public int size() It returns the total number of elements in the

collection.

8 public void clear() It removes the total number of elements from

the collection.

9 public boolean It is used to search an element.

contains(Object element)
10 public boolean It is used to search the specified collection in

containsAll(Collection<?> c) the collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the

runtime type of the returned array is that of the

specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> It returns a possibly parallel Stream with the

parallelStream() collection as its source.

16 default Stream<E> stream() It returns a sequential Stream with the

collection as its source.

17 default Spliterator<E> It generates a Spliterator over the specified

spliterator() elements in the collection.

18 public boolean equals(Object It matches two collections.

element)

19 int hashCode() It returns the hash code number of the

collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction

only.

Methods of Iterator interface

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

hasNext() it returns false.

2 public Object next() It returns the element and moves the cursor pointer to the

next element.

3 public void It removes the last elements returned by the iterator. It is

remove() less used.

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.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new 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.

It inherits the AbstractList class and implements List interface.

The important points about the Java ArrayList class are:

○ Java ArrayList class can contain duplicate elements.


○ Java ArrayList class maintains insertion order.

○ Java ArrayList class is non synchronized.

○ 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:

1. ArrayList<int> al = ArrayList<int>(); // does not work


2. ArrayList<Integer> al = new ArrayList<Integer>(); // works fine

○ 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() It is used to build an empty array list.

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

element) position in a list.

boolean add(E e) It is used to append the specified element at the end of a list.

boolean It is used to append all of the elements in the specified

addAll(Collection<? collection to the end of this list, in the order that they are

extends E> c) returned by the specified collection's iterator.

boolean addAll(int It is used to append all the elements in the specified

index, Collection<? collection, starting at the specified position of the list.

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.

boolean isEmpty() It returns true if the list is empty, otherwise false.

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.

Object[] toArray() It is used to return an array containing all of the elements in

this list in the correct order.


<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in

this list in the correct order.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean It returns true if the list contains the specified element.

contains(Object o)

int indexOf(Object o) It is used to return the index in this list of the first occurrence

of the specified element, or -1 if the List does not contain this

element.

E remove(int index) It is used to remove the element present at the specified

position in the list.

boolean It is used to remove the first occurrence of the specified

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

removeIf(Predicate< the given predicate.

? super E> filter)

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

replaceAll(UnaryOpe specified element.

rator<E> operator)

void It is used to retain all the elements in the list that are present

retainAll(Collection< in the specified collection.

?> c)
E set(int index, E It is used to replace the specified element in the list, present at

element) the specified position.

void It is used to sort the elements of the list on the basis of the

sort(Comparator<? specified comparator.

super E> c)

Spliterator<E> It is used to create a spliterator over the elements in a list.

spliterator()

List<E> subList(int It is used to fetch all the elements that lies within the given

fromIndex, int range.

toIndex)

int size() It is used to return the number of elements present in the list.

void trimToSize() It is used to trim the capacity of this ArrayList instance to be

the list's current size.


Java Non-generic Vs. Generic Collection

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.

Let's see the old non-generic example of creating a Java collection.

1. ArrayList list=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

1. ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist

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.*;

public class ArrayListExample1{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist

list.add("Mango");//Adding object in arraylist

list.add("Apple");

list.add("Banana");

list.add("Grapes");

//Printing the arraylist object


System.out.println(list);

Iterating ArrayList using Iterator

import java.util.*;

public class ArrayListExample2{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist

list.add("Mango");//Adding object in arraylist

list.add("Apple");

list.add("Banana");

list.add("Grapes");

//Traversing list through Iterator

Iterator itr=list.iterator();//getting the Iterator

while(itr.hasNext()){//check if iterator has the elements

System.out.println(itr.next());//printing the element and move to next

Iterating ArrayList using For-each loop


Let's see an example to traverse the ArrayList elements using the for-each loop

FileName: ArrayListExample3.java

import java.util.*;

public class ArrayListExample3{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist

list.add("Mango");//Adding object in arraylist

list.add("Apple");

list.add("Banana");

list.add("Grapes");

//Traversing list through for-each loop

for(String fruit:list)

System.out.println(fruit);

Get and Set ArrayList


The get() method returns the element at the specified index, whereas the set() method
changes the element.

How to Sort ArrayList

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{

public static void main(String args[]){

//Creating a list of fruits

List<String> list1=new ArrayList<String>();

list1.add("Mango");

list1.add("Apple");

list1.add("Banana");

list1.add("Grapes");

//Sorting the list

Collections.sort(list1);

//Traversing list through the for-each loop

for(String fruit:list1)

System.out.println(fruit);

System.out.println("Sorting numbers...");
//Creating a list of numbers

List<Integer> list2=new ArrayList<Integer>();

list2.add(21);

list2.add(11);

list2.add(51);

list2.add(1);

//Sorting the list

Collections.sort(list2);

//Traversing list through the for-each loop

for(Integer number:list2)

System.out.println(number);

Ways to iterate the elements of the collection in Java

There are various ways to traverse the collection elements:

1. By Iterator interface.

2. By for-each loop.

3. By ListIterator interface.

4. By for loop.

User-defined class objects in Java ArrayList


Let's see an example where we are storing Student class object in an array list.

class Student{

int rollno;

String name;

int age;

Student(int rollno,String name,int age){

this.rollno=rollno;

this.name=name;

this.age=age;

—--------

import java.util.*;

class ArrayList5{

public static void main(String args[]){

//Creating user-defined class objects

Student s1=new Student(101,"Sonoo",23);

Student s2=new Student(102,"Ravi",21);

Student s2=new Student(103,"Hanumat",25);


//creating arraylist

ArrayList<Student> al=new ArrayList<Student>();

al.add(s1);//adding Student class object

al.add(s2);

al.add(s3);

//Getting Iterator

Iterator itr=al.iterator();

//traversing elements of ArrayList object

while(itr.hasNext()){

Student st=(Student)itr.next();

System.out.println(st.rollno+" "+st.name+" "+st.age);

Size and Capacity of an ArrayList

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.*;

public class SizeCapacity

public static void main(String[] args) throws Exception

ArrayList<Integer> al = new ArrayList<Integer>();

System.out.println("The size of the array is: " + al.size());

Output:

The size of the array is: 0

Explanation: The output makes sense as we have not done anything with the array list. Now
observe the following program.

import java.util.*;

public class SizeCapacity1


{

public static void main(String[] args) throws Exception

ArrayList<Integer> al = new ArrayList<Integer>(10);

System.out.println("The size of the array is: " + al.size());

Output:

The size of the array is: 0

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.

The important points about Java LinkedList are:

○ Java LinkedList class can contain duplicate elements.

○ Java LinkedList class maintains insertion order.

○ Java LinkedList class is non synchronized.

○ In Java LinkedList class, manipulation is fast because no shifting needs to occur.


○ Java LinkedList class can be used as a list, stack or queue.

Hierarchy of LinkedList class

As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class
and implements List and Deque interfaces.

Doubly Linked List

In the case of a doubly linked list, we can add or remove elements from both sides.

Constructors of Java LinkedList

Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collec It is used to construct a list containing the elements of the

tion<? extends specified collection, in the order, they are returned by the

E> c) collection's iterator.


Methods of Java LinkedList

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

E element) position index in a list.

boolean It is used to append all of the elements in the specified

addAll(Collection<? collection to the end of this list, in the order that they are

extends E> c) returned by the specified collection's iterator.

boolean It is used to append all of the elements in the specified

addAll(Collection<? collection to the end of this list, in the order that they are

extends E> c) returned by the specified collection's iterator.

boolean addAll(int It is used to append all the elements in the specified collection,

index, Collection<? starting at the specified position of the list.

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.

void clear() It is used to remove all the elements from a list.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean It is used to return true if a list contains a specified element.

contains(Object o)

Iterator<E> It is used to return an iterator over the elements in a deque in

descendingIterator( reverse sequential order.

E element() It is used to retrieve the first element of a list.

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.

E getLast() It is used to return the last element in a list.

int indexOf(Object It is used to return the index in a list of the first occurrence of

o) the specified element, or -1 if the list does not contain any

element.

int It is used to return the index in a list of the last occurrence of

lastIndexOf(Object the specified element, or -1 if the list does not contain any

o) element.

ListIterator<E> It is used to return a list-iterator of the elements in proper

listIterator(int sequence, starting at the specified position in the list.

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)

boolean offerLast(E It inserts the specified element at the end of a list.

e)

E peek() It retrieves the first element of a list

E peekFirst() It retrieves the first element of a list or returns null if a list is

empty.

E peekLast() It retrieves the last element of a list or returns null if a list is

empty.

E poll() It retrieves and removes the first element of a list.

E pollFirst() It retrieves and removes the first element of a list, or returns

null if a list is empty.


E pollLast() It retrieves and removes the last element of a list, or returns null

if a list is empty.

E pop() It pops an element from the stack represented by a list.

void push(E e) It pushes an element onto the stack represented by a list.

E remove() It is used to retrieve and removes the first element of a list.

E remove(int index) It is used to remove the element at the specified position in a

list.

boolean It is used to remove the first occurrence of the specified

remove(Object o) element in a list.

E removeFirst() It removes and returns the first element from a list.


boolean It is used to remove the first occurrence of the specified

removeFirstOccurre element in a list (when traversing the list from head to tail).

nce(Object o)

E removeLast() It removes and returns the last element from a list.

boolean It removes the last occurrence of the specified element in a list

removeLastOccurre (when traversing the list from head to tail).

nce(Object o)

E set(int index, E It replaces the element at the specified position in a list with

element) the specified element.

Object[] toArray() It is used to return an array containing all the elements in a list

in proper sequence (from first to the last element).

<T> T[] toArray(T[] It returns an array containing all the elements in the proper

a) sequence (from first to the last element); the runtime type of

the returned array is that of the specified array.


int size() It is used to return the number of elements in a list.

Java LinkedList Example


import java.util.*;

public class LinkedList1{

public static void main(String args[]){

LinkedList<String> al=new LinkedList<String>();

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());

}
}

Difference Between ArrayList and LinkedList


ArrayList and LinkedList both implement the List interface and maintain insertion order. Both
are non-synchronized classes.

However, there are many differences between the ArrayList and LinkedList classes that are
given below.

ArrayList LinkedList

1) ArrayList internally uses a dynamic array to LinkedList internally uses a doubly

store the elements. linked list to store the elements.

2) Manipulation with ArrayList is slow Manipulation with LinkedList is

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

other elements are shifted in memory. is required in memory.

3) An ArrayList class can act as a list only LinkedList class can act as a list and

because it implements List only. queue both because it implements

List and Deque interfaces.


4) ArrayList is better for storing and LinkedList is better for manipulating

accessing data. data.

5) The memory location for the elements of The location for the elements of a

an ArrayList is contiguous. linked list is not contagious.

6) Generally, when an ArrayList is initialized, a There is no case of default capacity

default capacity of 10 is assigned to the in a LinkedList. In LinkedList, an

ArrayList. empty list is created when a

LinkedList is initialized.

7) To be precise, an ArrayList is a resizable LinkedList implements the doubly

array. linked list of the list interface.

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.

○ Since the elements of an ArrayList are stored more compact as compared to a


LinkedList; therefore, the ArrayList is more cache-friendly as compared to the
LinkedList. Thus, chances for the cache miss are less in an ArrayList as compared to
a LinkedList. Generally, it is considered that a LinkedList is poor in cache-locality.

○ Memory overhead in the LinkedList is more as compared to the ArrayList. It is


because, in a LinkedList, we have two extra links (next and previous) as it is required
to store the address of the previous and the next nodes, and these links consume
extra space. Such links are not present in an ArrayList.

Java ListIterator Interface


ListIterator Interface is used to traverse the element in a backward and forward direction.

ListIterator Interface declaration


1. public interface ListIterator<E> extends Iterator<E>

Methods of Java ListIterator Interface:

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

hasNext() traversing the list in the forward direction.

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

nextIndex() by a subsequent call to next()

boolean This method returns true if this list iterator has more elements while

hasPrevious( traversing the list in the reverse direction.

E previous() This method returns the previous element in the list and moves the

cursor position backward.

E This method returns the index of the element that would be returned

previousInde by a subsequent call to previous().

x()

void This method removes the last element from the list that was returned

remove() by next() or previous() methods

void set(E e) This method replaces the last element returned by next() or previous()

methods with the specified element.

Example of ListIterator Interface


import java.util.*;

public class ListIteratorExample1{


public static void main(String args[]){

List<String> al=new ArrayList<String>();

al.add("Amit");

al.add("Vijay");

al.add("Kumar");

al.add(1,"Sachin");

ListIterator<String> itr=al.listIterator();

System.out.println("Traversing elements in forward direction");

while(itr.hasNext()){

System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());

System.out.println("Traversing elements in backward direction");

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.

The important points about Java HashSet class are:

○ HashSet stores the elements by using a mechanism called hashing.


○ HashSet contains unique elements only.

○ HashSet allows null value.

○ HashSet class is non synchronized.

○ HashSet doesn't maintain the insertion order. Here, elements are inserted on the
basis of their hashcode.

○ HashSet is the best approach for search operations.

○ The initial default capacity of HashSet is 16

Difference between List and Set

A list can contain duplicate elements whereas Set contains unique elements only.

Methods of Java HashSet class

Various methods of Java HashSet class are as follows:

SN Modi Method Description


fier
&
Type

1) boolea add(E e) It is used to add the specified element to this set if it is

n not already present.

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

instance: the elements themselves are not cloned.

4) boolea contains( It is used to return true if this set contains the specified

n Object o) element.

5) boolea isEmpty() It is used to return true if this set contains no elements.

6) Iterato iterator() It is used to return an iterator over the elements in this

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.

8) int size() It is used to return the number of elements in the set.

Java HashSet Example

Let's see a simple example of HashSet. Notice, the elements iterate in an unordered
collection.

import java.util.*;
class HashSet1{

public static void main(String args[]){

//Creating HashSet and adding elements

HashSet<String> set=new HashSet();

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.

The important points about the Java LinkedHashSet class are:

○ Java LinkedHashSet class contains unique elements only like HashSet.

○ Java LinkedHashSet class provides all optional set operations and permits null
elements.

○ Java LinkedHashSet class is non-synchronized.

○ Java LinkedHashSet class maintains insertion order.


Note: Keeping the insertion order in the LinkedHashset has some additional costs, both in terms
of extra memory and extra CPU cycles. Therefore, if it is not required to maintain the insertion
order, go for the lighter-weight HashMap or the HashSet instead.

Hierarchy of LinkedHashSet class

The LinkedHashSet class extends the HashSet class, which implements the Set interface.
The Set interface inherits Collection and Iterable interfaces in hierarchical order.

LinkedHashSet Class Declaration

Let's see the declaration for java.util.LinkedHashSet class.

1. public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable,


Serializable

Constructors of Java LinkedHashSet Class

Constructor Description

HashSet() It is used to construct a default HashSet.

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

capacity) given integer value capacity.

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.

Java LinkedHashSet Example

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{

public static void main(String args[]){

//Creating HashSet and adding elements

LinkedHashSet<String> set=new LinkedHashSet();

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.

The important points about the Java TreeSet class are:

○ Java TreeSet class contains unique elements only like HashSet.

○ Java TreeSet class access and retrieval times are quiet fast.

○ Java TreeSet class doesn't allow null element.

○ Java TreeSet class is non synchronized.

○ Java TreeSet class maintains ascending order.

○ The TreeSet can only allow those generic types that are comparable. For example The
Comparable interface is being implemented by the StringBuffer class.

Synchronization of The TreeSet 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.

1. TreeSet treeSet = new TreeSet();

Hierarchy of TreeSet class


As shown in the above diagram, the Java TreeSet class implements the NavigableSet
interface. The NavigableSet interface extends SortedSet, Set, Collection and Iterable
interfaces in hierarchical order.

TreeSet Class Declaration

Let's see the declaration for java.util.TreeSet class.

1. public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>,


Cloneable, Serializable

Constructors of Java TreeSet Class

Constructor Description

TreeSet() It is used to construct an empty tree set that will be sorted in

ascending order according to the natural order of the tree set.

TreeSet(Collection<? It is used to build a new tree set that contains the elements of

extends E> c) the collection c.

TreeSet(Comparator<? It is used to construct an empty tree set that will be sorted

super E> comparator) according to given comparator.

TreeSet(SortedSet<E> It is used to build a TreeSet that contains the elements of the

s) given SortedSet.
Methods of Java TreeSet Class

Method Description

boolean add(E e) It is used to add the specified element to this set

if it is not already present.

boolean addAll(Collection<? extends It is used to add all of the elements in the

E> c) specified collection to this set.

E ceiling(E e) It returns the equal or closest greatest element

of the specified element from the set, or null

there is no such element.

Comparator<? super E> comparator() It returns a comparator that arranges elements

in order.

Iterator descendingIterator() It is used to iterate the elements in descending

order.

NavigableSet descendingSet() It returns the elements in reverse order.


E floor(E e) It returns the equal or closest least element of

the specified element from the set, or null there

is no such element.

SortedSet headSet(E toElement) It returns the group of elements that are less

than the specified element.

NavigableSet headSet(E toElement, It returns the group of elements that are less

boolean inclusive) than or equal to(if, inclusive is true) the specified

element.

E higher(E e) It returns the closest greatest element of the

specified element from the set, or null there is no

such element.

Iterator iterator() It is used to iterate the elements in ascending

order.

E lower(E e) It returns the closest least element of the

specified element from the set, or null there is no

such element.
E pollFirst() It is used to retrieve and remove the lowest(first)

element.

E pollLast() It is used to retrieve and remove the highest(last)

element.

Spliterator spliterator() It is used to create a late-binding and fail-fast

spliterator over the elements.

NavigableSet subSet(E fromElement, It returns a set of elements that lie between the

boolean fromInclusive, E toElement, given range.

boolean toInclusive)

SortedSet subSet(E fromElement, E It returns a set of elements that lie between the

toElement)) given range which includes fromElement and

excludes toElement.

SortedSet tailSet(E fromElement) It returns a set of elements that are greater than

or equal to the specified element.


NavigableSet tailSet(E fromElement, It returns a set of elements that are greater than

boolean inclusive) or equal to (if, inclusive is true) the specified

element.

boolean contains(Object o) It returns true if this set contains the specified

element.

boolean isEmpty() It returns true if this set contains no elements.

boolean remove(Object o) It is used to remove the specified element from

this set if it is present.

void clear() It is used to remove all of the elements from this

set.

Object clone() It returns a shallow copy of this TreeSet

instance.

E first() It returns the first (lowest) element currently in

this sorted set.


E last() It returns the last (highest) element currently in

this sorted set.

int size() It returns the number of elements in this set.

Java TreeSet Examples

Java TreeSet Example 1:

Let's see a simple example of Java TreeSet.

FileName: TreeSet1.java

import java.util.*;

class TreeSet1{

public static void main(String args[]){

//Creating and adding elements

TreeSet<String> al=new TreeSet<String>();

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{

public static void main(String args[]){

TreeSet<Integer> set=new TreeSet<Integer>();

set.add(24);

set.add(66);

set.add(12);

set.add(15);

System.out.println("Lowest Value: "+set.pollFirst());

System.out.println("Highest Value: "+set.pollLast());

}
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.

ava Vector Constructors

Vector class supports four types of constructors. These are given below:

S Constructor Description
N

1) vector() It constructs an empty vector with the default size as 10.

2) vector(int initialCapacity) It constructs an empty vector with the specified initial

capacity and with its capacity increment equal to zero.

3) vector(int initialCapacity, It constructs an empty vector with the specified initial

int capacityIncrement) capacity and capacity increment.


4) Vector( Collection<? It constructs a vector that contains the elements of a

extends E> c) collection c.

Java Vector Methods

The following are the list of Vector class methods:

S Method Description
N

1) add() It is used to append the specified element in the given vector.

2) addAll() It is used to append all of the elements in the specified collection to

the end of this Vector.

3) addElement() It is used to append the specified component to the end of this

vector. It increases the vector size by one.

4) capacity() It is used to get the current capacity of this vector.

5) clear() It is used to delete all of the elements from this vector.


6) clone() It returns a clone of this vector.

7) contains() It returns true if the vector contains the specified element.

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.

1 elementAt() It is used to get the component at the specified index.

0)

1 elements() It returns an enumeration of the components of a vector.

1)

1 ensureCapac It is used to increase the capacity of the vector which is in use, if

2) ity() necessary. It ensures that the vector can hold at least the number of

components specified by the minimum capacity argument.

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

5) until all elements have been processed or the action throws an

exception.

1 get() It is used to get an element at the specified position in the vector.

6)

1 hashCode() It is used to get the hash code value of a vector.

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.

1 insertElemen It is used to insert the specified object as a component in the given

9) tAt() vector at the specified index.

2 isEmpty() It is used to check if this vector has no components.

0)
2 iterator() It is used to get an iterator over the elements in the list in proper

1) sequence.

2 lastElement() It is used to get the last component of the vector.

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

5) vector does not contain the element, it is unchanged.

2 removeAll() It is used to delete all the elements from the vector that are present in

6) the specified collection.

2 removeAllEle It is used to remove all elements from the vector and set the size of

7) ments() the vector to zero.


2 removeEleme It is used to remove the first (lowest-indexed) occurrence of the

8) nt() argument from the vector.

2 removeEleme It is used to delete the component at the specified index.

9) ntAt()

3 removeIf() It is used to remove all of the elements of the collection that satisfy

0) the given predicate.

3 removeRang It is used to delete all of the elements from the vector whose index is

1) e() between fromIndex, inclusive and toIndex, exclusive.

3 replaceAll() It is used to replace each element of the list with the result of

2) applying the operator to that element.

3 retainAll() It is used to retain only that element in the vector which is contained

3) in the specified collection.

3 set() It is used to replace the element at the specified position in the vector

4) with the specified element.


3 setElementAt It is used to set the component at the specified index of the vector to

5) () the specified object.

3 setSize() It is used to set the size of the given vector.

6)

3 size() It is used to get the number of components in the given vector.

7)

3 sort() It is used to sort the list according to the order induced by the

8) specified Comparator.

3 spliterator() It is used to create a late-binding and fail-fast Spliterator over the

9) elements in the list.

4 subList() It is used to get a view of the portion of the list between fromIndex,

0) inclusive, and toIndex, exclusive.

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)

Java Vector Example


import java.util.*;

public class VectorExample {

public static void main(String args[]) {

//Create a vector

Vector<String> vec = new Vector<String>();

//Adding elements using add() method of List

vec.add("Tiger");

vec.add("Lion");

vec.add("Dog");

vec.add("Elephant");

//Adding elements using addElement() method of Vector

vec.addElement("Rat");
vec.addElement("Cat");

vec.addElement("Deer");

System.out.println("Elements are: "+vec);

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.

Let's remove (pop) 18, 45, and 11 from the stack.


Empty Stack: If the stack has no element is known as an empty stack. When the stack is
empty the value of the top variable is -1.
When we push an element into the stack the top is increased by 1. In the following figure,

○ Push 12, top=0

○ 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.

Java Stack Class


In Java, Stack is a class that falls under the Collection framework that extends the Vector
class. It also implements interfaces List, Collection, Iterable, Cloneable, Serializable. It
represents the LIFO stack of objects. Before using the Stack class, we must import the
java.util package. The stack class arranged in the Collections framework hierarchy, as
shown below.
Stack Class Constructor
The Stack class contains only the default constructor that creates an empty stack.

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.

1. Stack stk = new Stack();


Or

1. Stack<type> stk = new Stack<>();

Where type denotes the type of stack like Integer, String, etc.

Methods of the Stack Class


We can perform push, pop, peek and search operation on the stack. The Java Stack class
provides mainly five methods to perform these operations. Along with this, it also provides
all the methods of the Java Vector class.

Metho Modifie Method Description


d r and
Type

empty() boolean The method checks the stack is empty or not.

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

returns the same element as the value of that function.

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

bject o) position of the object.

Stack Class empty() Method

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

1. public boolean empty()

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:

Is the stack empty? true

Elements in Stack: [78, 113, 90, 120]

Is the stack empty? false

Stack Class push() Method

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

1. public E push(E item)


Parameter: An item to be pushed onto the top of the stack.

Returns: The method returns the argument that we have passed as a parameter.

Stack Class pop() Method

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()

Returns: It returns an object that is at the top of the stack.

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

stack: [20, 13]

push -> 89

stack: [20, 13, 89]

push -> 90

stack: [20, 13, 89, 90]

push -> 11

stack: [20, 13, 89, 90, 11]

push -> 45

stack: [20, 13, 89, 90, 11, 45]

push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]

pop -> 18

stack: [20, 13, 89, 90, 11, 45]

pop -> 45

stack: [20, 13, 89, 90, 11]

pop -> 11

stack: [20, 13, 89, 90]

Stack Class peek() Method

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()

Returns: It returns the top elements of the stack.

Let's see an example of the peek() method.

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:

Stack: [Apple, Grapes, Mango, Orange]

Element at the top of the stack: Orange

Stack Class search() Method

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

1. public int search(Object o)

Parameter: o is the desired object to be searched.

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.

Let's see an example of the search() method.

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

Size of the Stack

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

1. public int size()

Let's see an example of the size() method of the Vector class.

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:

Is the stack empty or not? false

The stack size is: 5

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:

○ Using iterator() Method

○ Using forEach() Method

○ Using listIterator() Method

Using the iterator() Method

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()

Let's perform an iteration over the stack.

StackIterationExample1.java

1. import java.util.Iterator;
import java.util.Stack;

public class StackIterationExample1

public static void main (String[] args)

//creating an object of Stack class

Stack stk = new Stack();

//pushing elements into stack

stk.push("BMW");

stk.push("Audi");

stk.push("Ferrari");

stk.push("Bugatti");

stk.push("Jaguar");

//iteration over the stack

Iterator iterator = stk.iterator();

while(iterator.hasNext())

Object values = iterator.next();

System.out.println(values);
}

2. }

Output:

BMW

Audi

Ferrari

Bugatti

Jaguar

Using the forEach() Method

Java provides a forEach() method to iterate over the elements. The method is defined in the
Iterable and Stream interface.

Syntax

1. default void forEach(Consumer<super T>action)

Let's iterate over the stack using the forEach() method.

StackIterationExample2.java

import java.util.*;

public class StackIterationExample2


{

public static void main (String[] args)

//creating an instance of Stack class

Stack <Integer> stk = new Stack<>();

//pushing elements into stack

stk.push(119);

stk.push(203);

stk.push(988);

System.out.println("Iteration over the stack using forEach() Method:");

//invoking forEach() method for iteration over the stack

stk.forEach(n ->

System.out.println(n);

});

Output:

Iteration over the stack using forEach() Method:


119

203

988

Using listIterator() Method

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

1. ListIterator listIterator(int index)

Parameter: The method parses a parameter named index.

Returns: This method returns a list iterator over the elements, in sequence.

Exception: It throws IndexOutOfBoundsException if the index is out of range.

Let's iterate over the stack using the listIterator() method.

StackIterationExample3.java

import java.util.Iterator;

import java.util.ListIterator;

import java.util.Stack;

public class StackIterationExample3


{

public static void main (String[] args)

Stack <Integer> stk = new Stack<>();

stk.push(119);

stk.push(203);

stk.push(988);

ListIterator<Integer> ListIterator = stk.listIterator(stk.size());

System.out.println("Iteration over the Stack from top to bottom:");

while (ListIterator.hasPrevious())

Integer avg = ListIterator.previous();

System.out.println(avg);

Java Deque Interface


The interface called Deque is present in java.util package. It is the subtype of the interface
queue. The Deque supports the addition as well as the removal of elements from both ends
of the data structure. Therefore, a deque can be used as a stack or a queue. We know that
the stack supports the Last In First Out (LIFO) operation, and the operation First In First Out
is supported by a queue. As a deque supports both, either of the mentioned operations can
be performed on it. Deque is an acronym for "double ended queue".

Deque Interface declaration


1. public interface Deque<E> extends Queue<E>

Methods of Java Deque Interface

Metho Description
d

boolean It is used to insert the specified element into this deque and return true upon

add(obje success.

ct)

boolean It is used to insert the specified element into this deque.

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

poll() deque is empty.

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

peek() null if this deque is empty.

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

t() deque is empty.

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() deque is empty.


Boolean Inserts the element e at the front of the queue. If the insertion is successful,

offerFirs true is returned; otherwise, false.

t(e)

Object Inserts the element e at the tail of the queue. If the insertion is successful, true

offerLas is returned; otherwise, false.

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.

The important points about ArrayDeque class are:

○ Unlike Queue, we can add or remove elements from both sides.

○ Null elements are not allowed in the ArrayDeque.

○ ArrayDeque is not thread safe, in the absence of external synchronization.

○ ArrayDeque has no capacity restrictions.

○ ArrayDeque is faster than LinkedList and Stack.

ArrayDeque Hierarchy

The hierarchy of ArrayDeque class is given in the figure displayed at the right side of the
page.

ArrayDeque class declaration

Let's see the declaration for java.util.ArrayDeque class.

1. public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>,


Cloneable, Serializable

Java ArrayDeque Example

FileName: ArrayDequeExample.java

import java.util.*;

public class ArrayDequeExample {


public static void main(String[] args) {

//Creating Deque and adding elements

Deque<String> deque = new ArrayDeque<String>();

deque.add("Ravi");

deque.add("Vijay");

deque.add("Ajay");

//Traversing elements

for (String str : deque) {

System.out.println(str);

Output:

Ravi

Vijay

Ajay

Java ArrayDeque Example: offerFirst() and pollLast()

FileName: DequeExample.java
import java.util.*;

public class DequeExample {

public static void main(String[] args) {

Deque<String> deque=new ArrayDeque<String>();

deque.offer("arvind");

deque.offer("vimal");

deque.add("mukul");

deque.offerFirst("jai");

System.out.println("After offerFirst Traversal...");

for(String s:deque){

System.out.println(s);

//deque.poll();

//deque.pollFirst();//it is same as poll()

deque.pollLast();

System.out.println("After pollLast() Traversal...");

for(String s:deque){

System.out.println(s);

}
}

Output:

After offerFirst Traversal...

jai

arvind

vimal

mukul

After pollLast() Traversal...

jai

arvind

vimal

Java ArrayDeque Example: Book

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;

public class ArrayDequeExample {

public static void main(String[] args) {

Deque<Book> set=new ArrayDeque<Book>();

//Creating Books

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw


Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to Deque

set.add(b1);
set.add(b2);

set.add(b3);

//Traversing ArrayDeque

for(Book b:set){

System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

You might also like