KEMBAR78
JAVA Unit 4 5 Course Material 2 | PDF | Class (Computer Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
26 views125 pages

JAVA Unit 4 5 Course Material 2

The document provides an overview of the Java Collections Framework, which allows for the storage and manipulation of groups of objects through various interfaces and classes. It details the Collection interface, methods for adding, removing, and accessing elements, as well as specific implementations like ArrayList and LinkedList. Additionally, it explains the use of iterators and provides examples of common operations performed on collections.

Uploaded by

SHILPI BANSAL
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)
26 views125 pages

JAVA Unit 4 5 Course Material 2

The document provides an overview of the Java Collections Framework, which allows for the storage and manipulation of groups of objects through various interfaces and classes. It details the Collection interface, methods for adding, removing, and accessing elements, as well as specific implementations like ArrayList and LinkedList. Additionally, it explains the use of iterators and provides examples of common operations performed on collections.

Uploaded by

SHILPI BANSAL
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/ 125

ACEENGINEERING COLLEGE

UNIT IV
Collections in Java
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.

Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java


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

What is a framework in Java

o It provides readymade architecture.

o It represents a set of classes and interfaces.

o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:

1. Interfaces and its implementations, i.e., classes

2. Algorithm

Hierarchy of Collection Framework


Let us see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.
Methods of Collection interface

No. Method Description

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


collection.

2 public booleanaddAll(Collection<? It is used to insert the specified


extends E> c) collection elements in the invoking
collection.

3 public booleanremove(Object element) It is used to delete an element from the


collection.
4 public It is used to delete all the elements of
booleanremoveAll(Collection<?> c) the specified collection from the
invoking collection.

5 default booleanremoveIf(Predicate<? It is used to delete all the elements of


super E> filter) the collection that satisfy the specified
predicate.

6 public booleanretainAll(Collection<?> It is used to delete all the elements of


c) invoking 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 booleancontains(Object It is used to search an element.


element)

10 public It is used to search the specified


booleancontainsAll(Collection<?> c) collection in 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 booleanisEmpty() It checks if collection is empty.

15 default Stream<E>parallelStream() It returns a possibly parallel Stream


with the collection as its source.

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


collection as its source.
17 default Spliterator<E>spliterator() It generates a Spliterator over the
specified elements in the collection.

18 public booleanequals(Object element) It matches two collections.

19 public 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:

No. Method Description

1 public It returns true if the iterator has more elements otherwise


booleanhasNext() it returns false.

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

3 public void remove() It removes the last elements returned by the iterator. It is
less used.

Iterable Interface
The Iterable interface is the root interface for all the collection classes. The
Collection interface extends the Iterable interface and therefore all the subclasses of
Collection interface also implement the Iterable interface.

It contains only one abstract method. i.e.,

1. Iterator<T> iterator()

It returns the iterator over the elements of type T.


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 ( Objectobj), 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.

The classes that implement the List interface are given below.

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.

1. import java.util.*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }

Output:

Ravi
Vijay
Ravi
Ajay

Method Description

void add(int index, E element) It is used to insert the specified element at the
specified position in a list.

boolean add(E e) It is used to append the specified element at the


end of a list.

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


E> c) specified collection to the end of this list, in the
order that they are returned by the specified
collection's iterator.

boolean addAll(int index, Collection<? It is used to append all the elements in the
extends E> c) specified collection, starting at the specified
position of the list.

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


list.
void ensureCapacity(int It is used to enhance the capacity of an ArrayList
requiredCapacity) instance.

Eget(int index) It is used to fetch the element from the particular


position of the list.

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

Iterator()

listIterator()

int lastIndexOf(Object o) It is used to return the index in this list of the last
occurrence of the specified element, or -1 if the list
does not contain this 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.

booleancontains(Object o) It returns true if the list contains the specified


element

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 remove(Object o) It is used to remove the first occurrence of the
specified element.

boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.

booleanremoveIf(Predicate<? super E> It is used to remove all the elements from the list
filter) that satisfies the given predicate.

protected void removeRange(int It is used to remove all the elements lies within the
fromIndex, int toIndex) given range.

void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list
operator) with the specified element.

void retainAll(Collection<?> c) It is used to retain all the elements in the list that
are present in the specified collection.

E set(int index, E element) It is used to replace the specified element in the


list, present at the specified position.

void sort(Comparator<? super E> c) It is used to sort the elements of the list on the
basis of specified comparator.

Spliterator<E>spliterator() It is used to create spliterator over the elements in


a list.

List<E>subList(int fromIndex, int It is used to fetch all the elements lies within the
toIndex) given range.

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.
Change an Item
To modify an element, use the set() method and refer to the index number:

Example
cars.set(0,"Opel");

Remove an Item
To remove an element, use the remove() method and refer to the index
number:

Example
cars.remove(0);

To remove all the elements in the ArrayList, use the clear() method:

Example
cars.clear();

ArrayList Size
To find out how many elements an ArrayList have, use the size method:

Example
cars.size();
Loop Through an ArrayList
Loop through the elements of an ArrayList with a for loop, and use
the size() method to specify how many times the loop should run:

Example
publicclassMain{

publicstaticvoidmain(String[]args){

ArrayList<String> cars =newArrayList<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Ford");

cars.add("Mazda");

for(inti=0;i<cars.size();i++){

System.out.println(cars.get(i));

You can also loop through an ArrayList with the for-each loop:

Example
publicclassMain{

publicstaticvoidmain(String[]args){

ArrayList<String> cars =newArrayList<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Ford");
cars.add("Mazda");

for(Stringi: cars){

System.out.println(i);

Other Types
Elements in an ArrayList are actually objects. In the examples above, we
created elements (objects) of type "String". Remember that a String in Java
is an object (not a primitive type). To use other types, such as int, you must
specify an equivalent wrapper class: Integer. For other primitive types,
use: Boolean for boolean, Character for char, Double for double, etc:

Example
Create an ArrayList to store numbers (add elements of type Integer):

importjava.util.ArrayList;

publicclassMain{

publicstaticvoidmain(String[]args){

ArrayList<Integer>myNumbers=newArrayList<Integer>();

myNumbers.add(10);

myNumbers.add(15);

myNumbers.add(20);

myNumbers.add(25);

for(inti:myNumbers){

System.out.println(i);

}
}

Sort an ArrayList
Another useful class in the java.util package is the Collections class, which
include the sort() method for sorting lists alphabetically or numerically:

Example
Sort an ArrayList of Strings:

importjava.util.ArrayList;

importjava.util.Collections;// Import the Collections class

publicclassMain{

publicstaticvoidmain(String[]args){

ArrayList<String> cars =newArrayList<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Ford");

cars.add("Mazda");

Collections.sort(cars);// Sort cars

for(Stringi: cars){

System.out.println(i);

}
Example
Sort an ArrayList of Integers:

importjava.util.ArrayList;

importjava.util.Collections;// Import the Collections class

publicclassMain{

publicstaticvoidmain(String[]args){

ArrayList<Integer>myNumbers=newArrayList<Integer>();

myNumbers.add(33);

myNumbers.add(15);

myNumbers.add(20);

myNumbers.add(34);

myNumbers.add(8);

myNumbers.add(12);

Collections.sort(myNumbers);// Sort myNumbers

for(inti:myNumbers){

System.out.println(i);

LinkedList
Method Description

booleanadd(E e) It is used to append the specified element to


the end of a list.

void add(int index, E element) It is used to insert the specified element at


the specified position index in a list.

booleanaddAll(Collection<? extends E> It is used to append all of the elements in


c) the specified collection to the end of this list,
in the order that they are returned by the
specified collection's iterator.

booleanaddAll(Collection<? extends E> It is used to append all of the elements in


c) the specified collection to the end of this list,
in the order that they are returned by the
specified collection's iterator.

booleanaddAll(int index, Collection<? It is used to append all the elements in the


extends E> c) specified collection, starting at the specified
position of the list.

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.

booleancontains(Object o) It is used to return true if a list contains a


specified element.

Iterator<E>descendingIterator() It is used to return an iterator over the


elements in a deque in reverse sequential
order.

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


list.

Eget(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 o) It is used to return the index in a list of the


first occurrence of the specified element, or -
1 if the list does not contain any element.

int lastIndexOf(Object o) It is used to return the index in a list of the


last occurrence of the specified element, or -
1 if the list does not contain any element.

ListIterator<E>listIterator(int index) It is used to return a list-iterator of the


elements in proper sequence, starting at the
specified position in the list.

booleanoffer(E e) It adds the specified element as the last


element of a list.

booleanofferFirst(E e) It inserts the specified element at the front


of a list.

booleanofferLast(E e) It inserts the specified element at the end of


a list.

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.

booleanremove(Object o) It is used to remove the first occurrence of


the specified element in a list.

E removeFirst() It removes and returns the first element


from a list.

booleanremoveFirstOccurrence(Object o) It is used to remove the first occurrence of


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

E removeLast() It removes and returns the last element


from a list.

booleanremoveLastOccurrence(Object o) It removes the last occurrence of the


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

E set(int index, E element) It replaces the element at the specified


position in a list with 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[] a) It returns an array containing all the


elements in the proper 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

1. import java.util.*;
2. public class LinkedList1{
3. public static void main(String args[]){
4.
5. LinkedList<String> al=new LinkedList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output: Ravi
Vijay
Ravi
Ajay

Java LinkedList example to add elements


Here, we see different ways to add elements.
1. import java.util.*;
2. public class LinkedList2{
3. public static void main(String args[]){
4. LinkedList<String> ll=new LinkedList<String>();
5. System.out.println("Initial list of elements: "+ll);
6. ll.add("Ravi");
7. ll.add("Vijay");
8. ll.add("Ajay");
9. System.out.println("After invoking add(E e) method: "+ll);
10. //Adding an element at the specific position
11. ll.add(1, "Gaurav");
12. System.out.println("After invoking add(int index, E element) method:
"+ll);
13. LinkedList<String> ll2=new LinkedList<String>();
14. ll2.add("Sonoo");
15. ll2.add("Hanumat");
16. //Adding second list elements to the first list
17. ll.addAll(ll2);
18. System.out.println("After invoking addAll(Collection<? extends E> c)
method: "+ll);
19. LinkedList<String> ll3=new LinkedList<String>();
20. ll3.add("John");
21. ll3.add("Rahul");
22. //Adding second list elements to the first list at specific position
23. ll.addAll(1, ll3);
24. System.out.println("After invoking addAll(int index, Collection<? exte
nds E> c) method: "+ll);
25. //Adding an element at the first position
26. ll.addFirst("Lokesh");
27. System.out.println("After invoking addFirst(E e) method: "+ll);
28. //Adding an element at the last position
29. ll.addLast("Harsh");
30. System.out.println("After invoking addLast(E e) method: "+ll);
31.
32. }
33. }
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay,
Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]

Java LinkedList example to remove elements


Here, we see different ways to remove an element.

1. import java.util.*;
2. public class LinkedList3 {
3.
4. public static void main(String [] args)
5. {
6. LinkedList<String> ll=new LinkedList<String>();
7. ll.add("Ravi");
8. ll.add("Vijay");
9. ll.add("Ajay");
10. ll.add("Anuj");
11. ll.add("Gaurav");
12. ll.add("Harsh");
13. ll.add("Virat");
14. ll.add("Gaurav");
15. ll.add("Harsh");
16. ll.add("Amit");
17. System.out.println("Initial list of elements: "+ll);
18. //Removing specific element from arraylist
19. ll.remove("Vijay");
20. System.out.println("After invoking remove(object) method: "+ll);
21. //Removing element on the basis of specific position
22. ll.remove(0);
23. System.out.println("After invoking remove(index) method: "+ll);
24. LinkedList<String> ll2=new LinkedList<String>();
25. ll2.add("Ravi");
26. ll2.add("Hanumat");
27. // Adding new elements to arraylist
28. ll.addAll(ll2);
29. System.out.println("Updated list : "+ll);
30. //Removing all the new elements from arraylist
31. ll.removeAll(ll2);
32. System.out.println("After invoking removeAll() method: "+ll);
33. //Removing first element from the list
34. ll.removeFirst();
35. System.out.println("After invoking removeFirst() method: "+ll);
36. //Removing first element from the list
37. ll.removeLast();
38. System.out.println("After invoking removeLast() method: "+ll);
39. //Removing first occurrence of element from the list
40. ll.removeFirstOccurrence("Gaurav");
41. System.out.println("After invoking removeFirstOccurrence() method
: "+ll);
42. //Removing last occurrence of element from the list
43. ll.removeLastOccurrence("Harsh");
44. System.out.println("After invoking removeLastOccurrence() method
: "+ll);
45.
46. //Removing all the elements available in the list
47. ll.clear();
48. System.out.println("After invoking clear() method: "+ll);
49. }
50. }
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh,
Virat, Gaurav, Harsh, Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit,
Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh,
Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav,
Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []

Java LinkedList Example to reverse a list of elements

1. import java.util.*;
2. public class LinkedList4{
3. public static void main(String args[]){
4.
5. LinkedList<String> ll=new LinkedList<String>();
6. ll.add("Ravi");
7. ll.add("Vijay");
8. ll.add("Ajay");
9. //Traversing the list of elements in reverse order
10. Iterator i=ll.descendingIterator();
11. while(i.hasNext())
12. {
13. System.out.println(i.next());
14. }
15.
16. }
17. }
Output: Ajay
Vijay
Ravi

Java LinkedList Example: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity
){
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class LinkedListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new LinkedList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan"
,"Mc Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.
quantity);
29. }
30. }
31. }

Output:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

LinkedList implements the Collection interface. It uses a doubly linked list internally
to store the elements. It can store the duplicate elements. It maintains the insertion
order and is not synchronized. In LinkedList, the manipulation is fast because no
shifting is required.

Consider the following example.


1. import java.util.*;
2. public class TestJavaCollection2{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:

Ravi
Vijay
Ravi
Ajay

ArrayList and LinkedList both implements List interface and maintains insertion
order. Both are non synchronized classes.

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

ArrayList LinkedList

1) ArrayList internally uses a dynamic LinkedList internally uses a doubly linked


array to store the elements. list to store the elements.

2) Manipulation with ArrayList Manipulation with LinkedList is faster than


is slow because it internally uses an array. If ArrayList because it uses a doubly linked
any element is removed from the array, all list, so no bit shifting is required in memory.
the bits are shifted 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 data.
accessing data.

Vector

Constructors:

1. Vector(): Creates a default vector of the initial capacity is 10.


Vector<E> v = new Vector<E>();
2. Vector(int size): Creates a vector whose initial capacity is specified by
size.
Vector<E> v = new Vector<E>(int size);
3. Vector(int size, int incr): Creates a vector whose initial capacity is
specified by size and increment is specified by incr. It specifies the number
of elements to allocate each time that a vector is resized upward.
Vector<E> v = new Vector<E>(int size, int incr);
4. Vector(Collection c): Creates a vector that contains the elements of
collection c.
Vector<E> v = new Vector<E>(Collection c);

Example: The following implementation demonstrates how to create and


use a Vector.
• Java

// Java program to demonstrate the

// working of Vector
importjava.io.*;

importjava.util.*;

classVectorExample {

publicstaticvoidmain(String[] args)

// Size of the

// Vector

intn = 5;

// Declaring the Vector with

// initial size n

Vector<Integer> v = newVector<Integer>(n);

// Appending new elements at

// the end of the vector

for(inti = 1; i<= n; i++)

v.add(i);
// Printing elements

System.out.println(v);

// Remove element at index 3

v.remove(3);

// Displaying the vector

// after deletion

System.out.println(v);

// Printing elements one by one

for(inti = 0; i<v.size(); i++)

System.out.print(v.get(i) + " ");

Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5

Performing Various Operations on Vector class in Java


1. Adding Elements: In order to add the elements to the Vector, we use
the add() method. This method is overloaded to perform multiple operations
based on different parameters. They are:
• add(Object): This method is used to add an element at the end of
the Vector.
• add(int index, Object): This method is used to add an element at a
specific index in the Vector.
• Java

// Java code for adding the

// elements in Vector Class

importjava.util.*;

importjava.io.*;

classAddElementsToVector {

publicstaticvoidmain(String[] arg)

// create default vector

Vector v1 = newVector();

// Add elements using add() method

v1.add(1);
v1.add(2);

v1.add("geeks");

v1.add("forGeeks");

v1.add(3);

// print the vector to the console

System.out.println("Vector v1 is "+ v1);

// create generic vector

Vector<Integer> v2 = newVector<Integer>();

v2.add(1);

v2.add(2);

v2.add(3);

System.out.println("Vector v2 is "+ v2);

Output:
Vector v1 is [1, 2, geeks, forGeeks, 3]
Vector v2 is [1, 2, 3]
2. Changing Elements: After adding the elements, if we wish to change the
element, it can be done using the set() method. Since a Vector is indexed,
the element which we wish to change is referenced by the index of the
element. Therefore, this method takes an index and the updated element
which needs to be inserted at that index.
• Java

// Java code to change the

// elements in vector class

importjava.util.*;

publicclassUpdatingVector {

publicstaticvoidmain(String args[])

// Creating an empty Vector

Vector<Integer>vec_tor = newVector<Integer>();

// Use add() method to add elements in the vector

vec_tor.add(12);

vec_tor.add(23);

vec_tor.add(22);

vec_tor.add(10);

vec_tor.add(20);
// Displaying the Vector

System.out.println("Vector: "+ vec_tor);

// Using set() method to replace 12 with 21

System.out.println("The Object that is replaced is:


"

+ vec_tor.set(0, 21));

// Using set() method to replace 20 with 50

System.out.println("The Object that is replaced is:


"

+ vec_tor.set(4, 50));

// Displaying the modified vector

System.out.println("The new Vector is:"+ vec_tor);

Output
Vector: [12, 23, 22, 10, 20]
The Object that is replaced is: 12
The Object that is replaced is: 20
The new Vector is:[21, 23, 22, 10, 50]
3. Removing Elements: In order to remove an element from a Vector, we
can use the remove() method. This method is overloaded to perform multiple
operations based on different parameters. They are:
• remove(Object): This method is used to simply remove an object
from the Vector. If there are multiple such objects, then the first
occurrence of the object is removed.
• remove(int index): Since a Vector is indexed, this method takes an
integer value which simply removes the element present at that
specific index in the Vector. After removing the element, all the
elements are moved to the left to fill the space and the indices of
the objects are updated.
• Java

// Java code illustrating the removal

// of elements from vector

importjava.util.*;

importjava.io.*;

classRemovingElementsFromVector {

publicstaticvoidmain(String[] arg)

// create default vector of capacity 10

Vector v = newVector();

// Add elements using add() method


v.add(1);

v.add(2);

v.add("Geeks");

v.add("forGeeks");

v.add(4);

// removing first occurrence element at 1

v.remove(1);

// checking vector

System.out.println("after removal: "+ v);

Output:

after removal: [1, Geeks, forGeeks, 4]


4. Iterating the Vector: There are multiple ways to iterate through the
Vector. The most famous ways are by using the basic for loop in combination
with a get() method to get the element at a specific index and the advanced
for loop.
• Java

// Java program to iterate the elements


// in a Vector

importjava.util.*;

publicclassIteratingVector {

publicstaticvoidmain(String args[])

// create an instance of vector

Vector<String> v = newVector<>();

// Add elements using add() method

v.add("Geeks");

v.add("Geeks");

v.add(1, "For");

// Using the Get method and the

// for loop

for(inti = 0; i<v.size(); i++) {

System.out.print(v.get(i) + " ");


}

System.out.println();

// Using the for each loop

for(String str : v)

System.out.print(str + " ");

Output
Geeks For Geeks
Geeks For Geeks
Important points regarding Increment of vector capacity:
If the increment is specified, Vector will expand according to it in each
allocation cycle but if the increment is not specified then the vector’s capacity
gets doubled in each allocation cycle. Vector defines three protected data
member:

int capacityIncreament: Contains the increment value.

int elementCount: Number of elements currently in vector stored
in it.
• Object elementData[]: Array that holds the vector is stored in it.
Common Errors in Declaration of Vectors
• Vector throws an IllegalArgumentException if the InitialSize of the
vector defined is negative.
• If the specified collection is null, It throws NullPointerException.

Methods in Vector Class


METHOD DESCRIPTION

add(E e) Appends the specified element to the end of this Vector.

Inserts the specified element at the specified position in


add(int index, E element) this Vector.

addAll(Collection<? Appends all of the elements in the specified Collection to


extends E> c) the end of this Vector, in the order that they are returned
by the specified Collection’s Iterator.

Inserts all of the elements in the specified Collection into


addAll(int index, this Vector at the specified position.
Collection<? extends E> c)

Adds the specified component to the end of this vector,


addElement(E obj) increasing its size by one.

capacity() Returns the current capacity of this vector.

clear() Removes all of the elements from this Vector.

clone() Returns a clone of this vector.

contains(Object o) Returns true if this vector contains the specified element.

containsAll(Collection<?> Returns true if this Vector contains all of the elements in


c) the specified Collection.

Copies the components of this vector into the specified


copyInto(Object[] anArray) array.
METHOD DESCRIPTION

elementAt(int index) Returns the component at the specified index.

elements() Returns an enumeration of the components of this vector.

Increases the capacity of this vector, if necessary, to


ensure that it can hold at least the number of
ensureCapacity(int components specified by the minimum capacity
minCapacity) argument.

Compares the specified Object with this Vector for


equals(Object o) equality.

Returns the first component (the item at index 0) of this


firstElement() vector.

Performs the given action for each element of the Iterable


until all elements have been processed or the action
forEach(Consumer<? throws an exception.
super E> action)

Returns the element at the specified position in this


get(int index) Vector.

hashCode() Returns the hash code value for this Vector.

Returns the index of the first occurrence of the specified


element in this vector,
indexOf(Object o) or -1 if this vector does not contain the element.

Returns the index of the first occurrence of the specified


indexOf(Object o, int element in this vector, searching forwards from the index,
index) or returns -1 if the element is not found.
METHOD DESCRIPTION

insertElementAt(E obj, int Inserts the specified object as a component in this vector
index) at the specified index.

isEmpty() Tests if this vector has no components.

Returns an iterator over the elements in this list in a


iterator() proper sequence.

lastElement() Returns the last component of the vector.

Returns the index of the last occurrence of the specified


element in this vector,
lastIndexOf(Object o) or -1 if this vector does not contain the element.

Returns the index of the last occurrence of the specified


lastIndexOf(Object o, int element in this vector, searching backward from the
index) index, or returns -1 if the element is not found.

Returns a list iterator over the elements in this list (in


listIterator() proper sequence).

Returns a list iterator over the elements in this list (in


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

Vector uses a dynamic array to store the data elements. It is similar to ArrayList.
However, It is synchronized and contains many methods that are not the part of
Collection framework.

Consider the following example.


1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. v.add("Ayush");
6. v.add("Amit");
7. v.add("Ashish");
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:

Ayush
Amit
Ashish
Garima

Stack
n order to create a stack, we must import java.util.stack package and use
the Stack() constructor of this class. The below example creates an empty
Stack.
Stack<E> stack = new Stack<E>();
Here E is the type of Object.
Example:
• Java

// Java code for stack implementation

importjava.io.*;

importjava.util.*;

classTest
{

// Pushing element on the top of the stack

staticvoidstack_push(Stack<Integer> stack)

for(inti = 0; i< 5; i++)

stack.push(i);

// Popping element from the top of the stack

staticvoidstack_pop(Stack<Integer> stack)

System.out.println("Pop Operation:");

for(inti = 0; i< 5; i++)

Integer y = (Integer) stack.pop();

System.out.println(y);

}
// Displaying element on the top of the stack

staticvoidstack_peek(Stack<Integer> stack)

Integer element = (Integer) stack.peek();

System.out.println("Element on stack top: "+


element);

// Searching element in the stack

staticvoidstack_search(Stack<Integer> stack, intelement)

Integer pos = (Integer) stack.search(element);

if(pos == -1)

System.out.println("Element not found");

else

System.out.println("Element is found at
position: "+ pos);

}
publicstaticvoidmain (String[] args)

Stack<Integer> stack = newStack<Integer>();

stack_push(stack);

stack_pop(stack);

stack_push(stack);

stack_peek(stack);

stack_search(stack, 2);

stack_search(stack, 6);

Output:
Pop Operation:
4
3
2
1
0
Element on stack top: 4
Element is found at position: 3
Element not found

Performing various operations on Stack class


1. Adding Elements: In order to add an element to the stack, we can use
the push() method. This push() operation place the element at the top of the
stack.

• Java

// Java program to add the

// elements in the stack

importjava.io.*;

importjava.util.*;

classStackDemo {

// Main Method

publicstaticvoidmain(String[] args)

// Default initialization of Stack

Stack stack1 = newStack();

// Initialization of Stack

// using Generics

Stack<String> stack2 = newStack<String>();


// pushing the elements

stack1.push(4);

stack1.push("All");

stack1.push("Geeks");

stack2.push("Geeks");

stack2.push("For");

stack2.push("Geeks");

// Priniting the Stack Elements

System.out.println(stack1);

System.out.println(stack2);

Output:
[4, All, Geeks]
[Geeks, For, Geeks]
2. Accessing the Element: To retrieve or fetch the first element of the Stack
or the element present at the top of the Stack, we can use peek() method.
The element retrieved does not get deleted or removed from the Stack.
• Java
// Java program to demonstrate the accessing

// of the elements from the stack

importjava.util.*;

importjava.io.*;

publicclassStackDemo {

// Main Method

publicstaticvoidmain(String args[])

// Creating an empty Stack

Stack<String> stack = newStack<String>();

// Use push() to add elements into the Stack

stack.push("Welcome");

stack.push("To");

stack.push("Geeks");

stack.push("For");

stack.push("Geeks");
// Displaying the Stack

System.out.println("Initial Stack: "+ stack);

// Fetching the element at the head of the Stack

System.out.println("The element at the top of the"

+ " stack is: "+ stack.peek());

// Displaying the Stack after the Operation

System.out.println("Final Stack: "+ stack);

Output:
Initial Stack: [Welcome, To, Geeks, For, Geeks]
The element at the top of the stack is: Geeks
Final Stack: [Welcome, To, Geeks, For, Geeks]
3. Removing Elements: To pop an element from the stack, we can use
the pop() method. The element is popped from the top of the stack and is
removed from the same.
• Java

// Java program to demonstrate the removing

// of the elements from the stack

importjava.util.*;

importjava.io.*;
publicclassStackDemo {

publicstaticvoidmain(String args[])

// Creating an empty Stack

Stack<Integer> stack = newStack<Integer>();

// Use add() method to add elements

stack.push(10);

stack.push(15);

stack.push(30);

stack.push(20);

stack.push(5);

// Displaying the Stack

System.out.println("Initial Stack: "+ stack);

// Removing elements using pop() method

System.out.println("Popped element: "

+ stack.pop());

System.out.println("Popped element: "


+ stack.pop());

// Displaying the Stack after pop operation

System.out.println("Stack after pop operation "

+ stack);

Output:
Initial Stack: [10, 15, 30, 20, 5]
Popped element: 5
Popped element: 20
Stack after pop operation [10, 15, 30]

METHOD DESCRIPTION

It returns true if nothing is on the top of the stack. Else, returns false.
empty()

The stack is the subclass of Vector. It implements the last-in-first-out data structure,
i.e., Stack. The stack contains all of the methods of Vector class and also provides
its methods like booleanpush(), boolean peek(), boolean push(object o), which
defines its properties.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Ayush
Garvit
Amit
Ashish

Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an
ordered list that is used to hold the elements which are about to be processed.
There are various classes like PriorityQueue, Deque, and ArrayDeque which
implements the Queue interface.

Queue interface can be instantiated as:

1. Queue<String> q1 = new PriorityQueue();


2. Queue<String> q2 = new ArrayDeque();

There are various classes that implement the Queue interface, some of them are
given below.

PriorityQueue

PriorityQueue in Java
A PriorityQueue is used when the objects are supposed to be processed
based on the priority. It is known that a Queue follows the First-In-First-Out
algorithm, but sometimes the elements of the queue are needed to be
processed according to the priority, that’s when the PriorityQueue comes into
play. The PriorityQueue is based on the priority heap. The elements of the
priority queue are ordered according to the natural ordering, or by a
Comparator provided at queue construction time, depending on which
constructor is used.

In the below priority queue, an element with maximum ASCII value will have
the highest priority.
Declaration:

public class PriorityQueue<E> extends AbstractQueue<E> implements


Serializable

where E is the type of elements held in this queue

The class
implements Serializable, Iterable<E>, Collection<E>, Queue<E> interfaces
.
Few important points on Priority Queue are as follows:
• PriorityQueue doesn’t permit null.
• We can’t create PriorityQueue of Objects that are non-comparable
• PriorityQueue are unbound queues.
• The head of this queue is the least element with respect to the
specified ordering. If multiple elements are tied for least value, the
head is one of those elements — ties are broken arbitrarily.
• Since PriorityQueue is not thread-safe, so java
provides PriorityBlockingQueue class that implements
the BlockingQueue interface to use in java multithreading
environment.
• The queue retrieval operations poll, remove, peek,
and element access the element at the head of the queue.
• It provides O(log(n)) time for add and poll methods.
The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow null
values to be stored in the queue.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit Sharma");
6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue elements:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two elements:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }

Output:

head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
Deque Interface

Constructors of ArrayDeque class

1. ArrayDeque(): This constructor is used to create an empty ArrayDeque and


by default holds an initial capacity to hold 16 elements.
ArrayDeque<E>dq = new ArrayDeque<E>();
2. ArrayDeque(Collection<? extends E> c): This constructor is used to create
an ArrayDeque containing all the elements the same as that of the specified
collection.
ArrayDeque<E>dq = new ArrayDeque<E>(Collection col);
3. ArrayDeque(int numofElements): This constructor is used to create an
empty ArrayDeque and holds the capacity to contain a specified number of
elements.

ArrayDeque<E>dq = new ArrayDeque<E>(int numofElements);


Example:

• Java

// Java program to demonstrate few functions of

// ArrayDeque in Java

importjava.util.*;

publicclassArrayDequeDemo

publicstaticvoidmain(String[] args)
{

// Initializing an deque

Deque<Integer>de_que = newArrayDeque<Integer>(10);

// add() method to insert

de_que.add(10);

de_que.add(20);

de_que.add(30);

de_que.add(40);

de_que.add(50);

for(Integer element :de_que)

System.out.println("Element : "+ element);

System.out.println("Using clear() ");

// clear() method

de_que.clear();

// addFirst() method to insert at start


de_que.addFirst(564);

de_que.addFirst(291);

// addLast() method to insert at end

de_que.addLast(24);

de_que.addLast(14);

System.out.println("Above elements are removed now");

// Iterator() :

System.out.println("Elements of deque using Iterator :");

for(Iterator itr = de_que.iterator(); itr.hasNext();)

System.out.println(itr.next());

// descendingIterator() : to reverse the deque order

System.out.println("Elements of deque in reverse order


:");

for(Iterator dItr = de_que.descendingIterator();

dItr.hasNext();)
{

System.out.println(dItr.next());

// element() method : to get Head element

System.out.println("\nHead Element using element(): "+

de_que.element());

// getFirst() method : to get Head element

System.out.println("Head Element using getFirst(): "+

de_que.getFirst());

// getLast() method : to get last element

System.out.println("Last Element using getLast(): "+

de_que.getLast());

// toArray() method :

Object[] arr = de_que.toArray();

System.out.println("\nArraySize : "+ arr.length);

System.out.print("Array elements : ");


for(inti=0; i<arr.length ; i++)

System.out.print(" "+ arr[i]);

// peek() method : to get head

System.out.println("\nHeadelement : "+ de_que.peek());

// poll() method : to get head

System.out.println("Head element poll : "+ de_que.poll());

// push() method :

de_que.push(265);

de_que.push(984);

de_que.push(2365);

// remove() method : to get head

System.out.println("Head element remove : "+


de_que.remove());

System.out.println("The final array is: "+de_que);

Output:
Element : 10
Element : 20
Element : 30
Element : 40
Element : 50
Using clear()
Above elements are removed now
Elements of deque using Iterator :
291
564
24
14
Elements of deque in reverse order :
14
24
564
291

Head Element using element(): 291


Head Element using getFirst(): 291
Last Element using getLast(): 14

Array Size : 4
Array elements : 291 564 24 14
Head element : 291
Head element poll : 291
Head element remove : 2365
The final array is: [984, 265, 564, 24, 14]

Performing Various Operations on the ArrayDeque class

Let’s see how to perform a few frequently used operations on the ArrayDeque.
1. Adding Elements: In order to add an element to the ArrayDeque, we can use
the methods add(), addFirst(), addLast(), offer(), offerFirst(), offerLast()
methods.
• add()
• addFirst()
• addLast()
• offer()
• offerFirst()
• offerLast()

• Java

// Java program to demonstrate the

// addition of elements in ArrayDeque

importjava.io.*;

importjava.util.*;

publicclassAddingElementsToArrayDeque {

publicstaticvoidmain(String[] args)

// Initializing a deque

// since deque is an interface

// it is assigned the

// ArrayDeque class

Deque<String>dq = newArrayDeque<String>();
// add() method to insert

dq.add("The");

dq.addFirst("To");

dq.addLast("Geeks");

// offer() method to insert

dq.offer("For");

dq.offerFirst("Welcome");

dq.offerLast("Geeks");

// printing Elements of ArrayDeque to the console

System.out.println("ArrayDeque : "+ dq);

Output:
ArrayDeque : [Welcome, To, The, Geeks, For, Geeks]
2. Accessing the Elements: After adding the elements, if we wish to access the
elements, we can use inbuilt methods like getFirst(), getLast(), etc.
• getFirst()
• getLast()
• peek()
• peekFirst()
• peekLast()

• Java
// Java program to access the

// elements of ArrayDeque

importjava.util.*;

importjava.io.*;

publicclassAccessingElementsOfArrayDeque {

publicstaticvoidmain(String args[])

// Creating an empty ArrayDeque

ArrayDeque<String>de_que

= newArrayDeque<String>();

// Use add() method to add elements into the Deque

de_que.add("Welcome");

de_que.add("To");

de_que.add("Geeks");

de_que.add("4");

de_que.add("Geeks");

// Displaying the ArrayDeque


System.out.println("ArrayDeque: "+ de_que);

// Displaying the First element

System.out.println("The first element is: "

+ de_que.getFirst());

// Displaying the Last element

System.out.println("The last element is: "

+ de_que.getLast());

Output:
ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
The first element is: Welcome
The last element is: Geeks
3. Removing Elements: In order to remove an element from a deque, there are
various methods available. Since we can also remove from both the ends, the
deque interface provides us with removeFirst(), removeLast() methods. Apart
from that, this interface also provides us with
the poll(), pop(), pollFirst(), pollLast() methods where pop() is used to remove
and return the head of the deque. However, poll() is used because this offers the
same functionality as pop() and doesn’t return an exception when the deque is
empty.
• remove()
• removeFirst()
• removeLast()
• poll()
• pollFirst()
• pollLast()
• pop()
• Java

// Java program to demonstrate the

// removal of elements in deque

importjava.util.*;

publicclassRemoveElementsOfArrayDeque {

publicstaticvoidmain(String[] args)

// Initializing a deque

Deque<String>dq = newArrayDeque<String>();

// add() method to insert

dq.add("One");

// addFirst inserts at the front

dq.addFirst("Two");

// addLast inserts at the back


dq.addLast("Three");

// print elements to the console

System.out.println("ArrayDeque : "+ dq);

// remove element as a stack from top/front

System.out.println(dq.pop());

// remove element as a queue from front

System.out.println(dq.poll());

// remove element from front

System.out.println(dq.pollFirst());

// remove element from back

System.out.println(dq.pollLast());

Output:

ArrayDeque : [Two, One, Three]


Two
One
Three
null
4. Iterating through the Deque: Since a deque can be iterated from both the
directions, the iterator method of the deque interface provides us two ways to
iterate. One from the first and the other from the back.
• iterator()
• descendingIterator()

• Java

// Java program to demonstrate the

// iteration of elements in deque

importjava.util.*;

publicclassIterateArrayDeque {

publicstaticvoidmain(String[] args)

// Initializing an deque

Deque<String>dq = newArrayDeque<String>();

// add() method to insert

// at the back

dq.add("For");
// add element at the front

dq.addFirst("Geeks");

// add element at the back

dq.addLast("Geeks");

dq.add("is so good");

// Iterate using Iterator interface

// from the front of the queue

for(Iterator itr = dq.iterator(); itr.hasNext();) {

System.out.print(itr.next() + " ");

System.out.println();

// Iterate in reverse

// sequence in a queue

for(Iterator itr = dq.descendingIterator();

itr.hasNext();) {

System.out.print(itr.next() + " ");


}

Output:
Geeks For Geeks is so good
is so good Geeks For Geeks

Methods in ArrayDeque

Here, Element is the type of elements stored by ArrayDeque.

METHOD DESCRIPTION

The method inserts a particular element at the end of


add(Element e) the deque.

Adds all of the elements in the specified collection at the


end of this deque, as if by calling addLast(E) on each one,
addAll(Collection<? extends in the order that they are returned by the collection’s
E> c) iterator.

The method inserts particular element at the start of the


addFirst(Element e) deque.

The method inserts a particular element at the end of


addLast(Element e) the deque. It is similar to the add() method

clear() The method removes all deque elements.

clone() The method copies the deque.


METHOD DESCRIPTION

The method checks whether a deque contains the


contains(Obj) element or not

element() The method returns element at the head of the deque

Performs the given action for each element of the


forEach(Consumer<? super Iterable until all elements have been processed or the
E> action) action throws an exception.

getFirst() The method returns first element of the deque

getLast() The method returns last element of the deque

isEmpty() The method checks whether the deque is empty or not.

iterator() Returns an iterator over the elements in this deque.

offer(Element e) The method inserts element at the end of deque.

offerFirst(Element e) The method inserts element at the front of deque.

offerLast(Element e) The method inserts element at the end of the deque.

peek() The method returns head element without removing it.

poll() The method returns head element and also removes it

The method pops out an element for stack represented


pop() by deque
METHOD DESCRIPTION

The method pushes an element onto stack represented


push(Element e) by deque

remove() The method returns head element and also removes it

Removes a single instance of the specified element from


remove(Object o) this deque.

Removes all of this collection’s elements that are also


contained in the specified collection (optional
removeAll(Collection<?> c) operation).

removeFirst() The method returns the first element and also removes it

Removes the first occurrence of the specified element in


removeFirstOccurrence this deque (when traversing the deque from head to
(Object o) tail).

removeIf(Predicate<? super Removes all of the elements of this collection that satisfy
Element> filter) the given predicate.

removeLast() The method returns the last element and also removes it

Removes the last occurrence of the specified element in


removeLastOccurrence this deque (when traversing the deque from head to
(Object o) tail).

Retains only the elements in this collection that are


contained in the specified collection (optional
retainAll(Collection<?> c) operation).
METHOD DESCRIPTION

size() Returns the number of elements in this deque.

Creates a late-binding and fail-fast Spliterator over the


spliterator() elements in this deque.

Returns an array containing all of the elements in this


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

Returns an array containing all of the elements in this


deque in proper sequence (from first to the last
element); the runtime type of the returned array is that
toArray(T[] a) of the specified array.

Methods declared in interface java.util.Deque

METHOD DESCRIPTION

Returns an iterator over the elements in this deque in reverse


descendingIterator() sequential order.

Retrieves, but does not remove, the first element of this deque,
peekFirst() or returns null if this deque is empty.

Retrieves, but does not remove, the last element of this deque,
peekLast() or returns null if this deque is empty.

Retrieves and removes the first element of this deque, or returns


pollFirst() null if this deque is empty.
METHOD DESCRIPTION

Retrieves and removes the last element of this deque, or returns


pollLast() null if this deque is empty.

Gautam
Karan
Ajay

Set Interface

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:

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

o HashSet contains unique elements only.

o HashSet allows null value.

o HashSet class is non synchronized.

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

o HashSet is the best approach for search operations.

o The initial default capacity of HashSet is 16, and the load factor is 0.75.

Difference between List and Set


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

Hierarchy of HashSet class


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

HashSet class declaration


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

1. public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cl


oneable, Serializable

Constructors of Java HashSet class

SN Constructor Description

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

2) HashSet(int capacity) It is used to initialize the capacity of the hash set to the
given integer value capacity. The capacity grows
automatically as elements are added to the HashSet.

3) HashSet(int capacity, float It is used to initialize the capacity of the hash set to the
loadFactor) given integer value capacity and the specified load factor.

4) HashSet(Collection<? It is used to initialize the hash set by using the elements


extends E> c) of the collection c.

Methods of Java HashSet class


Various methods of Java HashSet class are as follows:

Features of Java - Javatpoint

SN Modifier & Method Description


Type

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


this set if it is 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) boolean contains(Object It is used to return true if this set contains


o) the specified element.

5) boolean isEmpty() It is used to return true if this set contains


no elements.

6) Iterator<E> iterator() It is used to return an iterator over the


elements in this set.

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


o) from this set if it is present.

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


in the set.

9) Spliterator<E> spliterator() It is used to create a late-binding and fail-


fast Spliterator over the elements in the set.

Java HashSet Example


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

1. import java.util.*;
2. class HashSet1{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet();
6. set.add("One");
7. set.add("Two");
8. set.add("Three");
9. set.add("Four");
10. set.add("Five");
11. Iterator<String> i=set.iterator();
12. while(i.hasNext())
13. {
14. System.out.println(i.next());
15. }
16. }
17. }
Five
One
Four
Two
Three

Java HashSet example ignoring duplicate elements


In this example, we see that HashSet doesn't allow duplicate elements.

1. import java.util.*;
2. class HashSet2{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Ajay
Vijay
Ravi

Java HashSet example to remove elements


Here, we see different ways to remove an element.

1. import java.util.*;
2. class HashSet3{
3. public static void main(String args[]){
4. HashSet<String> set=new HashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Arun");
8. set.add("Sumit");
9. System.out.println("An initial list of elements: "+set);
10. //Removing specific element from HashSet
11. set.remove("Ravi");
12. System.out.println("After invoking remove(object) method: "+set);
13. HashSet<String> set1=new HashSet<String>();
14. set1.add("Ajay");
15. set1.add("Gaurav");
16. set.addAll(set1);
17. System.out.println("Updated List: "+set);
18. //Removing all the new elements from HashSet
19. set.removeAll(set1);
20. System.out.println("After invoking removeAll() method: "+set);
21. //Removing elements on the basis of specified condition
22. set.removeIf(str->str.contains("Vijay"));
23. System.out.println("After invoking removeIf() method: "+set);
24. //Removing all the elements available in the set
25. set.clear();
26. System.out.println("After invoking clear() method: "+set);
27. }
28. }
An initial list of elements: [Vijay, Ravi, Arun, Sumit]
After invoking remove(object) method: [Vijay, Arun, Sumit]
Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]
After invoking removeAll() method: [Vijay, Arun, Sumit]
After invoking removeIf() method: [Arun, Sumit]
After invoking clear() method: []

Java HashSet from another Collection

1. import java.util.*;
2. class HashSet4{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("Ravi");
6. list.add("Vijay");
7. list.add("Ajay");
8.
9. HashSet<String> set=new HashSet(list);
10. set.add("Gaurav");
11. Iterator<String> i=set.iterator();
12. while(i.hasNext())
13. {
14. System.out.println(i.next());
15. }
16. }
17. }
Vijay
Ravi
Gaurav
Ajay

Java HashSet Example: Book


Let's see a HashSet example where we are adding books to set and printing all the
books.

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity
){
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class HashSetExample {
15. public static void main(String[] args) {
16. HashSet<Book> set=new HashSet<Book>();
17. //Creating Books
18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
19. Book b2=new Book(102,"Data Communications & Networking","Forouzan"
,"Mc Graw Hill",4);
20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
21. //Adding Books to HashSet
22. set.add(b1);
23. set.add(b2);
24. set.add(b3);
25. System.out.println(set);
26. //Traversing HashSet
27. for(Book b:set){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.
quantity);
29. }
30. }
31. }

Output:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

Java HashSet
A HashSet is a collection of items where every item is unique, and it is found
in the java.util package:

Example
Create a HashSet object called cars that will store strings:

importjava.util.HashSet;// Import the HashSet class

HashSet<String> cars =newHashSet<String>();


Add Items
The HashSet class has many useful methods. For example, to add items to it,
use the add() method:

Example
// Import the HashSet class

importjava.util.HashSet;

publicclassMain{

publicstaticvoidmain(String[]args){

HashSet<String> cars =newHashSet<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Ford");

cars.add("BMW");

cars.add("Mazda");

System.out.println(cars);

Try it Yourself »

Note: In the example above, even though BMW is added twice it only
appears once in the set because every item in a set has to be unique.

Check If an Item Exists


To check whether an item exists in a HashSet, use the contains() method:

Example
cars.contains("Mazda");

Try it Yourself »

Remove an Item
To remove an item, use the remove() method:

Example
cars.remove("Volvo");

Try it Yourself »

To remove all items, use the clear() method:

Example
cars.clear();

Try it Yourself »

HashSet Size
To find out how many items there are, use the size method:

Example
cars.size();

Try it Yourself »

Loop Through a HashSet


Loop through the items of an HashSet with a for-each loop:
Example
for(Stringi: cars){

System.out.println(i);

Try it Yourself »

Other Types
Items in an HashSet are actually objects. In the examples above, we created
items (objects) of type "String". Remember that a String in Java is an object
(not a primitive type). To use other types, such as int, you must specify an
equivalent wrapper class: Integer. For other primitive types, use: Boolean for
boolean, Character for char, Double for double, etc:

Example
Use a HashSet that stores Integer objects:

importjava.util.HashSet;

publicclassMain{

publicstaticvoidmain(String[]args){

// Create a HashSet object called numbers

HashSet<Integer> numbers =newHashSet<Integer>();

// Add values to the set

numbers.add(4);

numbers.add(7);

numbers.add(8);
// Show which numbers between 1 and 10 are in the set

for(inti=1;i<=10;i++){

if(numbers.contains(i)){

System.out.println(i+" was found in the set.");

}else{

System.out.println(i+" was not found in the set.");

Constructors of LinkedHashSet class:

1. LinkedHashSet(): This constructor is used to create a default HashSet


LinkedHashSet<E>hs = new LinkedHashSet<E>();
2. LinkedHashSet(Collection C): Used in initializing the HashSet with the
elements of the collection C.
LinkedHashSet<E>hs = new LinkedHashSet<E>(Collection c);
3. LinkedHashSet(int size): Used to initialize the size of the LinkedHashSet
with the integer mentioned in the parameter.
LinkedHashSet<E>hs = new LinkedHashSet<E>(int size);
4. LinkedHashSet(int capacity, float fillRatio): Can be used to initialize
both the capacity and the fill ratio, also called the load capacity of the
LinkedHashSet with the arguments mentioned in the parameter. When the
number of elements exceeds the capacity of the hash set is multiplied with
the fill ratio thus expanding the capacity of the LinkedHashSet.

LinkedHashSet<E>hs = new LinkedHashSet<E>(int capacity, int fillRatio);


Example:
• Java
// Java Program to illustrate the LinkedHashSet

importjava.util.LinkedHashSet;

publicclassLinkedHashSetExample

// Main Method

publicstaticvoidmain(String[] args)

LinkedHashSet<String>linkedset =

newLinkedHashSet<String>();

// Adding element to LinkedHashSet

linkedset.add("A");

linkedset.add("B");

linkedset.add("C");

linkedset.add("D");

// This will not add new element as A already exists

linkedset.add("A");

linkedset.add("E");
System.out.println("Size of LinkedHashSet = "+

linkedset.size());

System.out.println("Original LinkedHashSet:"+ linkedset);

System.out.println("Removing D from LinkedHashSet: "+

linkedset.remove("D"));

System.out.println("Trying to Remove Z which is not "+

"present: "+ linkedset.remove("Z"));

System.out.println("Checking if A is present="+

linkedset.contains("A"));

System.out.println("Updated LinkedHashSet: "+ linkedset);

Performing various operations on the LinkedHashSet class

Let’s see how to perform a few frequently used operations on the LinkedHashSet.

1. Adding Elements: In order to add an element to the LinkedHashSet, we can use the add() method.
This is different from HashSet because in HashSet, the insertion order is not retained but it is
retained in the LinkedHashSet.

• Java

// Java program for adding

// elements to LinkedHashSet

import java.util.*;

import java.io.*;

class AddingElementsToLinkedHashSet {
public static void main(String[] args)

// create an instance of

// LinkedHashSet

LinkedHashSet<String>hs

= new LinkedHashSet<String>();

// Elements are added using add() method

// insertion order is maintained

hs.add("Geek");

hs.add("For");

hs.add("Geeks");

// print elements to the console

System.out.println("LinkedHashSet : " + hs);

Output:

LinkedHashSet : [Geek, For, Geeks]

2. Removing the Elements: The values can be removed from the LinkedHashSet using
the remove() method.

• Java

// Java program to remove elements

// from LinkedHashSet

import java.io.*;

import java.util.*;

class RemoveElementsFromLinkedHashSet {
public static void main(String[] args)

// create an instance of

// LinkedHashSet

LinkedHashSet<String>hs

= new LinkedHashSet<String>();

// Elements are added using add() method

hs.add("Geek");

hs.add("For");

hs.add("Geeks");

hs.add("A");

hs.add("B");

hs.add("Z");

// print elements to the console

System.out.println("Initial HashSet " + hs);

// Removing the element b

hs.remove("B");

System.out.println("After removing element " + hs);

// Returns false if the element is not present

System.out.println(hs.remove("AC"));

Output:
Initial HashSet [Geek, For, Geeks, A, B, Z]

After removing element [Geek, For, Geeks, A, Z]

false

3. Iterating through the LinkedHashSet: Iterate through the elements of LinkedHashSet


using the iterator() method. The most famous one is to use the enhanced for loop.

• Java

// Java code to demonstrate

// the iterating over LinkedHashSet

import java.io.*;

import java.util.*;

class IteratingLinkedHashSet {

public static void main(String[] args)

// Instantiate an object of Set

// Since LinkedHashSet implements Set

// Set points to LinkedHashSet

Set<String>hs = new LinkedHashSet<String>();

// Elements are added using add() method

hs.add("Geek");

hs.add("For");

hs.add("Geeks");

hs.add("A");

hs.add("B");

hs.add("Z");
// Iterating though the LinkedHashSet

Iteratoritr = hs.iterator();

while (itr.hasNext())

System.out.print(itr.next() + ", ");

System.out.println();

//Object

// Using enhanced for loop

for (String s :hs)

System.out.print(s + ", ");

System.out.println();

Output:

Geek, For, Geeks, A, B, Z,

Geek, For, Geeks, A, B, Z,

Methods of LinkedHashSet

Here, E is the type of element stored.

METHOD DESCRIPTION

spliterator() Creates a late-binding and fail-fast Spliterator over the elements in this set.

Methods declared in class java.util.AbstractSet

METHOD DESCRIPTION

equals(Object o) Compares the specified object with this set for equality.

hashCode() Returns the hash code value for this set.


METHOD DESCRIPTION

removeAll(Collection Removes from this set all of its elements that are contained in the
c) specified collection (optional operation).

Methods declared in class java.util.AbstractCollection

METHOD DESCRIPTION

addAll(Collection<? Adds all of the elements in the specified collection to this collection
extends E> c) (optional operation).

containsAll Returns true if this collection contains all of the elements in the specified
(Collection<?> c) collection.

retainAll(Collection<?> Retains only the elements in this collection that are contained in the
c) specified collection (optional operation).

toArray() Returns an array containing all of the elements in this collection.

Returns an array containing all of the elements in this collection; the


toArray(T[] a) runtime type of the returned array is that of the specified array.

toString() Returns a string representation of this collection.

Methods declared in interface java.util.Collection

METHOD DESCRIPTION

parallelStream() Returns a possibly parallel Stream with this collection as its source.

removeIf(Predicate<?
super
Removes all of the elements of this collection that satisfy the given
E> filter) predicate.
METHOD DESCRIPTION

stream() Returns a sequential Stream with this collection as its source.

Methods declared in class java.util.HashSet

METHOD DESCRIPTION

add(E e) Adds the specified element to this set if it is not already present.

clear() Removes all of the elements from this set.

Returns a shallow copy of this HashSet instance: the elements themselves are
clone() not cloned.

contains(Object
o) Returns true if this set contains the specified element.

isEmpty() Returns true if this set contains no elements.

iterator() Returns an iterator over the elements in this set.

remove(Object o) Removes the specified element from this set if it is present.

size() Returns the number of elements in this set (its cardinality).

Methods declared in interface java.lang.Iterable

METHOD DESCRIPTION

forEach(Consumer<?
super
Performs the given action for each element of the Iterable until all
T> action) elements have been processed or the action throws an exception.

Methods declared in interface java.util.Set


METHOD DESCRIPTION

This method is used to add a specific element to the set. The function adds
the element only if the specified element is not already present in the set
add(element) else the function returns False if the element is already present in the Set.

This method is used to append all of the elements from the mentioned
collection to the existing set. The elements are added randomly without
addAll(Collection c) following any specific order.

This method is used to remove all the elements from the set but not
clear() delete the set. The reference for the set still exists.

This method is used to check whether a specific element is present in the


contains(element) Set or not.

This method is used to check whether the set contains all the elements
present in the given collection or not. This method returns true if the set
containsAll(Collection contains all the elements and returns false if any of the elements are
c) missing.

This method is used to get the hashCode value for this instance of the Set.
It returns an integer value which is the hashCode value for this instance of
hashCode() the Set.

isEmpty() This method is used to check whether the set is empty or not.

This method is used to return the iterator of the set. The elements from
iterator() the set are returned in random order.

This method is used to remove the given element from the set. This
method returns True if the specified element is present in the Set
remove(element) otherwise it returns False.

This method is used to remove all the elements from the collection which
removeAll(collection)
are present in the set. This method returns true if this set changed as a
METHOD DESCRIPTION

result of the call.

This method is used to retain all the elements from the set which are
mentioned in the given collection. This method returns true if this set
retainAll(collection) changed as a result of the call.

This method is used to get the size of the set. This returns an integer value
size() which signifies the number of elements.

This method is used to form an array of the same elements as that of the
toArray() Set.

Returns an array containing all of the elements in this set; the runtime
toArray(T[] a) type of the returned array is that of the specified array.

Following is the difference between LinkedHashMap and LinekdHashSet:

importjava.util.Vector;

importjava.util.Enumeration;

publicclassEnumerationClass {

publicstaticvoidmain(String args[])

{
Enumeration months;

Vector<String>monthNames = newVector<>();

monthNames.add("January");

monthNames.add("Febraury");

monthNames.add("March");

monthNames.add("April");

monthNames.add("May");

monthNames.add("June");

monthNames.add("July");

monthNames.add("August");

monthNames.add("September");

monthNames.add("Octobor");

monthNames.add("November");

monthNames.add("December");

months = monthNames.elements();

while(months.hasMoreElements()) {

System.out.println(months.nextElement());

}
Output
January
Febraury
March
April
May
June
July
August
September
Octobor
November
December

Set Interface in Java is present in java.util package. It extends the Collection


interface. It represents the unordered set of elements which doesn't allow us to
store the duplicate items. We can store at most one null value in Set. Set is
implemented by HashSet, LinkedHashSet, and TreeSet.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();

HashSet
HashSet class implements Set Interface. It represents the collection that uses a
hash table for storage. Hashing is used to store the elements in the HashSet. It
contains unique items.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection7{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Vijay
Ravi
Ajay

LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It
extends the HashSet class and implements Set interface. Like HashSet, It also
contains unique elements. It maintains the insertion order and permits null
elements.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection8{
3. public static void main(String args[]){
4. LinkedHashSet<String> set=new LinkedHashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ravi");
8. set.add("Ajay");
9. Iterator<String> itr=set.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:

Ravi
Vijay
Ajay

SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its
elements. The elements of the SortedSet are arranged in the increasing (ascending)
order. The SortedSet provides the additional methods that inhibit the natural
ordering of the elements.

The SortedSet can be instantiated as:

1. SortedSet<data-type> set = new TreeSet();

TreeSet

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 Java TreeSet class are:

o Java TreeSet class contains unique elements only like HashSet.


o Java TreeSet class access and retrieval times are quiet fast.
o Java TreeSet class doesn't allow null element.
o Java TreeSet class is non synchronized.
o Java TreeSet class maintains ascending order.

Hierarchy of TreeSet class


As shown in the above diagram, 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<? extends It is used to build a new tree set that contains the
E> c) elements of the collection c.

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


E> comparator) be sorted according to given comparator.

TreeSet(SortedSet<E> s) It is used to build a TreeSet that contains the


elements of the given SortedSet.

Methods of Java TreeSet class

Method Description

booleanadd(E e) It is used to add the specified


element to this set if it is not already
present.

booleanaddAll(Collection<? extends E> c) It is used to add all of the elements


in the 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 comparator that arranged


elements in order.
Iterator descendingIterator() It is used 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, boolean It returns the group of elements that


inclusive) are less 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


booleanfromInclusive, E toElement, between the given range.
booleantoInclusive)

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


toElement)) between the 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


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

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


specified element.

booleanisEmpty() It returns true if this set contains no


elements.

booleanremove(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.

1. import java.util.*;
2. class TreeSet1{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> al=new TreeSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Test it Now

Output:

C++ vs Java
Ajay
Ravi
Vijay

Java TreeSet Example 2:


Let's see an example of traversing elements in descending order.

1. import java.util.*;
2. class TreeSet2{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ajay");
8. System.out.println("Traversing element through Iterator in descending or
der");
9. Iterator i=set.descendingIterator();
10. while(i.hasNext())
11. {
12. System.out.println(i.next());
13. }
14.
15. }
16. }
Test it Now

Output:

Traversing element through Iterator in descending order


Vijay
Ravi
Ajay
Traversing element through NavigableSet in descending order
Vijay
Ravi
Ajay

Java TreeSet Example 3:


Let's see an example to retrieve and remove the highest and lowest Value.

1. import java.util.*;
2. class TreeSet3{
3. public static void main(String args[]){
4. TreeSet<Integer> set=new TreeSet<Integer>();
5. set.add(24);
6. set.add(66);
7. set.add(12);
8. set.add(15);
9. System.out.println("Highest Value: "+set.pollFirst());
10. System.out.println("Lowest Value: "+set.pollLast());
11. }
12. }

Output:

Highest Value: 12
Lowest Value: 66

Java TreeSet Example 4:


In this example, we perform various NavigableSet operations.

1. import java.util.*;
2. class TreeSet4{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add("A");
6. set.add("B");
7. set.add("C");
8. set.add("D");
9. set.add("E");
10. System.out.println("Initial Set: "+set);
11.
12. System.out.println("Reverse Set: "+set.descendingSet());
13.
14. System.out.println("Head Set: "+set.headSet("C", true));
15.
16. System.out.println("SubSet: "+set.subSet("A", false, "E", true));
17.
18. System.out.println("TailSet: "+set.tailSet("C", false));
19. }
20. }

Output:

Initial Set: [A, B, C, D, E]


Reverse Set: [E, D, C, B, A]
Head Set: [A, B, C]
SubSet: [B, C, D, E]
TailSet: [D, E]

Java TreeSet Example 4:


In this example, we perform various SortedSetSet operations.

1. import java.util.*;
2. class TreeSet4{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add("A");
6. set.add("B");
7. set.add("C");
8. set.add("D");
9. set.add("E");
10.
11. System.out.println("Intial Set: "+set);
12.
13. System.out.println("Head Set: "+set.headSet("C"));
14.
15. System.out.println("SubSet: "+set.subSet("A", "E"));
16.
17. System.out.println("TailSet: "+set.tailSet("C"));
18. }
19. }
Output:
Intial Set: [A, B, C, D, E]
Head Set: [A, B]
SubSet: [A, B, C, D]
TailSet: [C, D, E]

Java TreeSet Example: Book


Let's see a TreeSet example where we are adding books to set and printing all the
books. The elements in TreeSet must be of a Comparable type. String and Wrapper
classes are Comparable by default. To add user-defined objects in TreeSet, you need
to implement the Comparable interface.

1. import java.util.*;
2. class Book implements Comparable<Book>{
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {

7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. public int compareTo(Book b) {
14. if(id>b.id){
15. return 1;
16. }else if(id<b.id){
17. return -1;
18. }else{
19. return 0;
20. }
21. }
22. }
23. public class TreeSetExample {
24. public static void main(String[] args) {
25. Set<Book> set=new TreeSet<Book>();
26. //Creating Books
27. Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
28. Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
29. Book b3=new Book(101,"Data Communications & Networking","Forouzan",
"Mc Graw Hill",4);
30. //Adding Books to TreeSet
31. set.add(b1);
32. set.add(b2);
33. set.add(b3);
34. //Traversing TreeSet
35. for(Book b:set){
36. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.qu
antity);
37. }
38. }
39. }

Output:

101 Data Communications & Networking Forouzan Mc Graw Hill 4


121 Let us C Yashwant Kanetkar BPB 8
233 Operating System Galvin Wiley 6
Java TreeSet class implements the Set interface that uses a tree for storage. Like
HashSet, TreeSet also contains unique elements. However, the access and retrieval
time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.

Consider the following example:

1. import java.util.*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Ajay
Ravi

Vijay

The class Date represents a specific instant in time, with millisecond


precision. The Date class of java.util package implements Serializable,
Cloneable and Comparable interface. It provides constructors and methods
to deal with date and time with java.
Constructors
• Date() : Creates date object representing current date and time.
• Date(long milliseconds) : Creates a date object for the given
milliseconds since January 1, 1970, 00:00:00 GMT.
• Date(int year, int month, int date)
• Date(int year, int month, int date, int hrs, int min)
• Date(int year, int month, int date, int hrs, int min, int sec)
• Date(String s)
Note : The last 4 constructors of the Date class are Deprecated.

// Java program to demonstrate constuctors of Date

importjava.util.*;

publicclassMain

publicstaticvoidmain(String[] args)

Date d1 = newDate();

System.out.println("Current date is "+ d1);

Date d2 = newDate(2323223232L);

System.out.println("Date represented is "+ d2 );

Output:
Current date is Tue Jul 12 18:35:37 IST 2016
Date represented is Wed Jan 28 02:50:23 IST 1970
Important Methods
• booleanafter(Date date) : Tests if current date is after the
given date.
• D1//current date
• D2// previous date
• D2.after(d1);//false
• booleanbefore(Date date) : Tests if current date is before
the given date.
• int compareTo(Date date) : Compares current date with
given date. Returns 0 if the argument Date is equal to the
Date; a value less than 0 if the Date is before the Date
argument; and a value greater than 0 if the Date is after
the Date argument.
• D1 Date d1=new Date();
• Date d2=new Date();
• D1.compareTo(d2)
• D2
• long getTime() : Returns the number of milliseconds
since January 1, 1970, 00:00:00 GMT represented by this
Date object.
• void setTime(long time) : Changes the current date and
time to given time.

// Program to demonstrate methods of Date class

importjava.util.*;

publicclassMain

publicstaticvoidmain(String[] args)

// Creating date

Date d1 = newDate(2000, 11, 21);

Date d2 = newDate(); // Current date

Date d3 = newDate(2010, 1, 3);


booleana = d3.after(d1);// true return

System.out.println("Date d3 comes after "+

"date d2: "+ a);

booleanb = d3.before(d2);

System.out.println("Date d3 comes before "+

"date d2: "+ b);

intc = d1.compareTo(d2);

System.out.println(c);

System.out.println("Miliseconds from Jan 1 "+

"1970 to date d1 is "+ d1.getTime());

System.out.println("Before setting "+d2);

d2.setTime(204587433443L);

System.out.println("After setting "+d2);

Output:
Date d3 comes after date d2: true
Date d3 comes before date d2: false
1
Miliseconds from Jan 1 1970 to date d1 is 60935500800000
Before setting Tue Jul 12 13:13:16 UTC 2016
After setting Fri Jun 25 21:50:33 UTC 1976

Calendar Class in Java with examples


• Difficulty Level : Medium
• Last Updated : 28 Aug, 2018
Calendar class in Java is an abstract class that provides methods for converting
date between a specific instant in time and a set of calendar fields such as
MONTH, YEAR, HOUR, etc. It inherits Object class and implements the
Comparable, Serializable, Cloneable interfaces.
As it is an Abstract class, so we cannot use a constructor to create an instance.
Instead, we will have to use the static method Calendar.getInstance() to
instantiate and implement a sub-class.
Calendar.getInstance(): return a Calendar instance based on the

current time in the default time zone with the default locale.
• Calendar.getInstance(TimeZone zone)
• Calendar.getInstance(Locale aLocale)
• Calendar.getInstance(TimeZone zone, Locale aLocale)
Java program to demonstrate getInstance() method:

// Date getTime(): It is used to return a

// Date object representing this

// Calendar's time value.

importjava.util.*;

publicclassCalendar1 {

publicstaticvoidmain(String args[])

{
Calendar c = Calendar.getInstance();

System.out.println("The Current Date is:"+ c.getTime());

Output:
The Current Date is:Tue Aug 28 11:10:40 UTC 2018
Important Methods and their usage

METHOD DESCRIPTION

abstract void add(int field, It is used to add or subtract the specified amount of time to
int amount) the given calendar field, based on the calendar’s rules.

int get(int field) It is used to return the value of the given calendar field.

abstract int It is used to return the maximum value for the given
getMaximum(int field) calendar field of this Calendar instance.

abstract int It is used to return the minimum value for the given
getMinimum(int field) calendar field of this Calendar instance.

It is used to return a Date object representing this Calendar’s


Date getTime() time value.</td

Below programs illustrate the above methods:


Program 1: Java program to demonstrate get() method.

// Program to demonstrate get() method

// of Calendar class

importjava.util.*;
publicclassCalendar2 {

publicstaticvoidmain(String[] args)

// creating Calendar object

Calendar calendar = Calendar.getInstance();

// Demonstrate Calendar's get()method

System.out.println("Current Calendar's Year: "+


calendar.get(Calendar.YEAR));

System.out.println("Current Calendar's Day: "+


calendar.get(Calendar.DATE));

System.out.println("Current MINUTE: "+


calendar.get(Calendar.MINUTE));

System.out.println("Current SECOND: "+


calendar.get(Calendar.SECOND));

Output:
Current Calendar's Year: 2018
Current Calendar's Day: 28
Current MINUTE: 10
Current SECOND: 45
Program 2: Java program to demonstrate getMaximum() method.

// Program to demonstrate getMaximum() method

// of Calendar class
importjava.util.*;

publicclassCalendar3 {

publicstaticvoidmain(String[] args)

// creating calendar object

Calendar calendar = Calendar.getInstance();

intmax = calendar.getMaximum(Calendar.DAY_OF_WEEK);

System.out.println("Maximum number of days in a week: "+ max);

max = calendar.getMaximum(Calendar.WEEK_OF_YEAR);

System.out.println("Maximum number of weeks in a year: "+ max);

Output:
Maximum number of days in a week: 7
Maximum number of weeks in a year: 53
Program 3: Java program to demonstrate the getMinimum() method.

// Program to demonstrate getMinimum() method

// of Calendar class
importjava.util.*;

publicclassCalendar4 {

publicstaticvoidmain(String[] args)

// creating calendar object

Calendar calendar = Calendar.getInstance();

intmin = calendar.getMinimum(Calendar.DAY_OF_WEEK);

System.out.println("Minimum number of days in week: "+ min);

min = calendar.getMinimum(Calendar.WEEK_OF_YEAR);

System.out.println("Minimum number of weeks in year: "+ min);

Output:
Minimum number of days in week: 1
Minimum number of weeks in year: 1
Program 4: Java program to demonstrate add() method.

// Program to demonstrate add() method

// of Calendar class

importjava.util.*;
publicclassCalendar5 {

publicstaticvoidmain(String[] args)

// creating calendar object

Calendar calendar = Calendar.getInstance();

calendar.add(Calendar.DATE, -15);

System.out.println("15 days ago: "+ calendar.getTime());

calendar.add(Calendar.MONTH, 4);

System.out.println("4 months later: "+ calendar.getTime());

calendar.add(Calendar.YEAR, 2);

System.out.println("2 years later: "+ calendar.getTime());

Output:
15 days ago: Mon Aug 13 11:10:57 UTC 2018
4 months later: Thu Dec 13 11:10:57 UTC 2018
2 years later: Sun Dec 13 11:10:57 UTC 2020

A StringTokenizer object internally maintains a current position within the


string to be tokenized. Some operations advance this current position past
the characters processed.
A token is returned by taking a substring of the string that was used to create
the StringTokenizer object.
Constructors:
StringTokenizer(String str) :
str is string to be tokenized.
Considers default delimiters like new line, space, tab,
carriage return and form feed.
StringTokenizer(String str, String delim) :
delim is set of delimiters that are used to tokenize
the given string.

StringTokenizer(String str, String delim, boolean flag):


The first two parameters have same meaning. The flag
serves following purpose.

If the flag is false, delimiter characters serve to


separate tokens. For example, if string is "hello geeks"
and delimiter is " ", then tokens are "hello" and "geeks".

If the flag is true, delimiter characters are


considered to be tokens. For example, if string is "hello
geeks" and delimiter is " ", then tokens are "hello", " "
and "geeks".

/* A Java program to illustrate working of StringTokenizer

class:*/

importjava.util.*;

publicclassNewClass

publicstaticvoidmain(String args[])

System.out.println("Using Constructor 1 - ");

StringTokenizer st1 =

newStringTokenizer("Hello Geeks How are you", " ");

while(st1.hasMoreTokens())

System.out.println(st1.nextToken());
System.out.println("Using Constructor 2 - ");

StringTokenizer st2 =

newStringTokenizer("JAVA : Code : String", " :");

while(st2.hasMoreTokens())

System.out.println(st2.nextToken());

System.out.println("Using Constructor 3 - ");

StringTokenizer st3 =

newStringTokenizer("JAVA : Code : String", " :", true);

while(st3.hasMoreTokens())

System.out.println(st3.nextToken());

Output :

Using Constructor 1 -
Hello
Geeks
How
are
you
Using Constructor 2 -
JAVA
Code
String
Using Constructor 3 -
JAVA

Class constructors

Sr.No. Constructor & Description

1 StringTokenizer(String str)
This constructor a string tokenizer for the specified string.

2 StringTokenizer(String str, String delim)


This constructor constructs string tokenizer for the specified string.

3 StringTokenizer(String str, String delim, booleanreturnDelims)


This constructor constructs a string tokenizer for the specified string.

Class methods

Sr.No. Method & Description

1 int countTokens()

This method calculates the number of times that this tokenizer's nextToken
method can be called before it generates an exception.

2 booleanhasMoreElements()
This method returns the same value as the hasMoreTokens method.

3 booleanhasMoreTokens()
This method tests if there are more tokens available from this tokenizer's string.

4 Object nextElement()
This method returns the same value as the nextToken method, except that its
declared return value is Object rather than String.

5 String nextToken()
This method returns the next token from this string tokenizer.

6 String nextToken(String delim)


This method returns the next token in this string tokenizer's string.

The BitSet class creates a special type of array that holds bit values. The BitSet
array can increase in size as needed. This makes it similar to a vector of bits. This
is a legacy class but it has been completely re-engineered in Java 2, version 1.4.
The BitSet defines the following two constructors.

Sr.No. Constructor & Description

1 BitSet( )
This constructor creates a default object.

2 BitSet(int size)
This constructor allows you to specify its initial size, i.e., the number of bits that it
can hold. All bits are initialized to zero.

BitSet implements the Cloneable interface and defines the methods listed in the
following table −

Sr.No. Method & Description

1 void and(BitSetbitSet)
ANDs the contents of the invoking BitSet object with those specified by bitSet.
The result is placed into the invoking object.

2 void andNot(BitSetbitSet)
For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared.

3 int cardinality( )
Returns the number of set bits in the invoking object.
4 void clear( )
Zeros all bits.

5 void clear(int index)


Zeros the bit specified by index.

6 void clear(int startIndex, int endIndex)


Zeros the bits from startIndex to endIndex.

7 Object clone( )
Duplicates the invoking BitSet object.

8 booleanequals(Object bitSet)
Returns true if the invoking bit set is equivalent to the one passed in bitSet.
Otherwise, the method returns false.

9 void flip(int index)


Reverses the bit specified by the index.

10 void flip(int startIndex, int endIndex)


Reverses the bits from startIndex to endIndex.

11 booleanget(int index)
Returns the current state of the bit at the specified index.

12 BitSetget(int startIndex, int endIndex)


Returns a BitSet that consists of the bits from startIndex to endIndex. The
invoking object is not changed.

13 int hashCode( )
Returns the hash code for the invoking object.

14 booleanintersects(BitSetbitSet)
Returns true if at least one pair of corresponding bits within the invoking object
and bitSet are 1.

15 booleanisEmpty( )
Returns true if all bits in the invoking object are zero.

16 int length( )
Returns the number of bits required to hold the contents of the invoking BitSet.
This value is determined by the location of the last 1 bit.

17
int nextClearBit(int startIndex)
Returns the index of the next cleared bit, (that is, the next zero bit), starting from
the index specified by startIndex.

18 int nextSetBit(int startIndex)


Returns the index of the next set bit (that is, the next 1 bit), starting from the
index specified by startIndex. If no bit is set, -1 is returned.

19 void or(BitSetbitSet)
ORs the contents of the invoking BitSet object with that specified by bitSet. The
result is placed into the invoking object.

20 void set(int index)


Sets the bit specified by index.

21 void set(int index, boolean v)


Sets the bit specified by index to the value passed in v. True sets the bit, false
clears the bit.

22 void set(int startIndex, int endIndex)


Sets the bits from startIndex to endIndex.

23 void set(int startIndex, int endIndex, boolean v)


Sets the bits from startIndex to endIndex, to the value passed in v. true sets the
bits, false clears the bits.
24 int size( )
Returns the number of bits in the invoking BitSet object.

25 String toString( )
Returns the string equivalent of the invoking BitSet object.

26 void xor(BitSetbitSet)
XORs the contents of the invoking BitSet object with that specified by bitSet. The
result is placed into the invoking object.

Example
The following program illustrates several of the methods supported by this data
structure −

Live Demo
importjava.util.BitSet;
publicclassBitSetDemo{

publicstaticvoidmain(Stringargs[]){
BitSet bits1 =newBitSet(16);
BitSet bits2 =newBitSet(16);

// set some bits


for(inti=0;i<16;i++){
if((i%2)==0) bits1.set(i);
if((i%5)!=0) bits2.set(i);
}

System.out.println("Initial pattern in bits1: ");


System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);

// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);

// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);

// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}

This will produce the following result −

Output
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}

Initial pattern in bits2:


{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}

bits2 AND bits1:


{2, 4, 6, 8, 12, 14}

bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}

bits2 XOR bits1:


{}

The BitSet class creates a special type of array that holds bit values. The BitSet
array can increase in size as needed. This makes it similar to a vector of bits. This
is a legacy class but it has been completely re-engineered in Java 2, version 1.4.
The BitSet defines the following two constructors.

Sr.No. Constructor & Description

1 BitSet( )
This constructor creates a default object.

2
BitSet(int size)
This constructor allows you to specify its initial size, i.e., the number of bits that it
can hold. All bits are initialized to zero.

BitSet implements the Cloneable interface and defines the methods listed in the
following table −

Sr.No. Method & Description


1 void and(BitSetbitSet)
ANDs the contents of the invoking BitSet object with those specified by bitSet.
The result is placed into the invoking object.

2 void andNot(BitSetbitSet)
For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared.

3 int cardinality( )
Returns the number of set bits in the invoking object.

4 void clear( )
Zeros all bits.

5 void clear(int index)


Zeros the bit specified by index.

6 void clear(int startIndex, int endIndex)


Zeros the bits from startIndex to endIndex.

7 Object clone( )
Duplicates the invoking BitSet object.

8 booleanequals(Object bitSet)
Returns true if the invoking bit set is equivalent to the one passed in bitSet.
Otherwise, the method returns false.

9 void flip(int index)


Reverses the bit specified by the index.

10 void flip(int startIndex, int endIndex)


Reverses the bits from startIndex to endIndex.

11 booleanget(int index)
Returns the current state of the bit at the specified index.
12 BitSetget(int startIndex, int endIndex)
Returns a BitSet that consists of the bits from startIndex to endIndex. The
invoking object is not changed.

13 int hashCode( )
Returns the hash code for the invoking object.

14 booleanintersects(BitSetbitSet)
Returns true if at least one pair of corresponding bits within the invoking object
and bitSet are 1.

15 booleanisEmpty( )
Returns true if all bits in the invoking object are zero.

16 int length( )
Returns the number of bits required to hold the contents of the invoking BitSet.
This value is determined by the location of the last 1 bit.

17
int nextClearBit(int startIndex)
Returns the index of the next cleared bit, (that is, the next zero bit), starting from
the index specified by startIndex.

18 int nextSetBit(int startIndex)


Returns the index of the next set bit (that is, the next 1 bit), starting from the
index specified by startIndex. If no bit is set, -1 is returned.

19 void or(BitSetbitSet)
ORs the contents of the invoking BitSet object with that specified by bitSet. The
result is placed into the invoking object.

20 void set(int index)


Sets the bit specified by index.

21 void set(int index, boolean v)


Sets the bit specified by index to the value passed in v. True sets the bit, false
clears the bit.

22 void set(int startIndex, int endIndex)


Sets the bits from startIndex to endIndex.

23 void set(int startIndex, int endIndex, boolean v)


Sets the bits from startIndex to endIndex, to the value passed in v. true sets the
bits, false clears the bits.

24
int size( )
Returns the number of bits in the invoking BitSet object.

25 String toString( )
Returns the string equivalent of the invoking BitSet object.

26 void xor(BitSetbitSet)
XORs the contents of the invoking BitSet object with that specified by bitSet. The
result is placed into the invoking object.

Example
The following program illustrates several of the methods supported by this data
structure −

Live Demo
importjava.util.BitSet;
publicclassBitSetDemo{

publicstaticvoidmain(Stringargs[]){
BitSet bits1 =newBitSet(16);
BitSet bits2 =newBitSet(16);

// set some bits


for(inti=0;i<16;i++){
if((i%2)==0) bits1.set(i);
if((i%5)!=0) bits2.set(i);
}

System.out.println("Initial pattern in bits1: ");


System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);
// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);

// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);

// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}

This will produce the following result −

Output
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}

Initial pattern in bits2:


{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}

bits2 AND bits1:


{2, 4, 6, 8, 12, 14}

bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}

bits2 XOR bits1:


{}

You might also like