JAVA Unit 4 5 Course Material 2
JAVA Unit 4 5 Course Material 2
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).
o It is optional.
2. Algorithm
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
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.
1. Iterator<T> iterator()
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.
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 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.
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.
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.
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.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the
basis of specified comparator.
List<E>subList(int fromIndex, int It is used to fetch all the elements lies within the
toIndex) given range.
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){
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){
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;
publicclassMain{
publicstaticvoidmain(String[]args){
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
for(Stringi: cars){
System.out.println(i);
}
Example
Sort an ArrayList of Integers:
importjava.util.ArrayList;
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);
for(inti:myNumbers){
System.out.println(i);
LinkedList
Method Description
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
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: []
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
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:
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.
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
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:
// working of Vector
importjava.io.*;
importjava.util.*;
classVectorExample {
publicstaticvoidmain(String[] args)
// Size of the
// Vector
intn = 5;
// initial size n
Vector<Integer> v = newVector<Integer>(n);
v.add(i);
// Printing elements
System.out.println(v);
v.remove(3);
// after deletion
System.out.println(v);
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
importjava.util.*;
importjava.io.*;
classAddElementsToVector {
publicstaticvoidmain(String[] arg)
Vector v1 = newVector();
v1.add(1);
v1.add(2);
v1.add("geeks");
v1.add("forGeeks");
v1.add(3);
Vector<Integer> v2 = newVector<Integer>();
v2.add(1);
v2.add(2);
v2.add(3);
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
importjava.util.*;
publicclassUpdatingVector {
publicstaticvoidmain(String args[])
Vector<Integer>vec_tor = newVector<Integer>();
vec_tor.add(12);
vec_tor.add(23);
vec_tor.add(22);
vec_tor.add(10);
vec_tor.add(20);
// Displaying the Vector
+ vec_tor.set(0, 21));
+ vec_tor.set(4, 50));
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
importjava.util.*;
importjava.io.*;
classRemovingElementsFromVector {
publicstaticvoidmain(String[] arg)
Vector v = newVector();
v.add(2);
v.add("Geeks");
v.add("forGeeks");
v.add(4);
v.remove(1);
// checking vector
Output:
importjava.util.*;
publicclassIteratingVector {
publicstaticvoidmain(String args[])
Vector<String> v = newVector<>();
v.add("Geeks");
v.add("Geeks");
v.add(1, "For");
// for loop
System.out.println();
for(String str : v)
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.
insertElementAt(E obj, int Inserts the specified object as a component in this vector
index) at the specified index.
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.
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
importjava.io.*;
importjava.util.*;
classTest
{
staticvoidstack_push(Stack<Integer> stack)
stack.push(i);
staticvoidstack_pop(Stack<Integer> stack)
System.out.println("Pop Operation:");
System.out.println(y);
}
// Displaying element on the top of the stack
staticvoidstack_peek(Stack<Integer> stack)
if(pos == -1)
else
System.out.println("Element is found at
position: "+ pos);
}
publicstaticvoidmain (String[] args)
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
• Java
importjava.io.*;
importjava.util.*;
classStackDemo {
// Main Method
publicstaticvoidmain(String[] args)
// Initialization of Stack
// using Generics
stack1.push(4);
stack1.push("All");
stack1.push("Geeks");
stack2.push("Geeks");
stack2.push("For");
stack2.push("Geeks");
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
importjava.util.*;
importjava.io.*;
publicclassStackDemo {
// Main Method
publicstaticvoidmain(String args[])
stack.push("Welcome");
stack.push("To");
stack.push("Geeks");
stack.push("For");
stack.push("Geeks");
// Displaying the 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
importjava.util.*;
importjava.io.*;
publicclassStackDemo {
publicstaticvoidmain(String args[])
stack.push(10);
stack.push(15);
stack.push(30);
stack.push(20);
stack.push(5);
+ stack.pop());
+ 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.
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.
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:
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.
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
• Java
// ArrayDeque in Java
importjava.util.*;
publicclassArrayDequeDemo
publicstaticvoidmain(String[] args)
{
// Initializing an deque
Deque<Integer>de_que = newArrayDeque<Integer>(10);
de_que.add(10);
de_que.add(20);
de_que.add(30);
de_que.add(40);
de_que.add(50);
// clear() method
de_que.clear();
de_que.addFirst(291);
de_que.addLast(24);
de_que.addLast(14);
// Iterator() :
System.out.println(itr.next());
dItr.hasNext();)
{
System.out.println(dItr.next());
de_que.element());
de_que.getFirst());
de_que.getLast());
// toArray() method :
// push() method :
de_que.push(265);
de_que.push(984);
de_que.push(2365);
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
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]
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
importjava.io.*;
importjava.util.*;
publicclassAddingElementsToArrayDeque {
publicstaticvoidmain(String[] args)
// Initializing a deque
// it is assigned the
// ArrayDeque class
Deque<String>dq = newArrayDeque<String>();
// add() method to insert
dq.add("The");
dq.addFirst("To");
dq.addLast("Geeks");
dq.offer("For");
dq.offerFirst("Welcome");
dq.offerLast("Geeks");
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[])
ArrayDeque<String>de_que
= newArrayDeque<String>();
de_que.add("Welcome");
de_que.add("To");
de_que.add("Geeks");
de_que.add("4");
de_que.add("Geeks");
+ de_que.getFirst());
+ 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
importjava.util.*;
publicclassRemoveElementsOfArrayDeque {
publicstaticvoidmain(String[] args)
// Initializing a deque
Deque<String>dq = newArrayDeque<String>();
dq.add("One");
dq.addFirst("Two");
System.out.println(dq.pop());
System.out.println(dq.poll());
System.out.println(dq.pollFirst());
System.out.println(dq.pollLast());
Output:
• Java
importjava.util.*;
publicclassIterateArrayDeque {
publicstaticvoidmain(String[] args)
// Initializing an deque
Deque<String>dq = newArrayDeque<String>();
// at the back
dq.add("For");
// add element at the front
dq.addFirst("Geeks");
dq.addLast("Geeks");
dq.add("is so good");
System.out.println();
// Iterate in reverse
// sequence in a queue
itr.hasNext();) {
Output:
Geeks For Geeks is so good
is so good Geeks For Geeks
Methods in ArrayDeque
METHOD DESCRIPTION
removeFirst() The method returns the first element and also removes it
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
METHOD DESCRIPTION
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.
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.
o HashSet doesn't maintain the insertion order. Here, elements are inserted on
the basis of their hashcode.
o The initial default capacity of HashSet is 16, and the load factor is 0.75.
SN Constructor Description
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.
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
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
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: []
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
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:
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:
Example
// Import the HashSet class
importjava.util.HashSet;
publicclassMain{
publicstaticvoidmain(String[]args){
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.
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 »
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 »
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){
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)){
}else{
importjava.util.LinkedHashSet;
publicclassLinkedHashSetExample
// Main Method
publicstaticvoidmain(String[] args)
LinkedHashSet<String>linkedset =
newLinkedHashSet<String>();
linkedset.add("A");
linkedset.add("B");
linkedset.add("C");
linkedset.add("D");
linkedset.add("A");
linkedset.add("E");
System.out.println("Size of LinkedHashSet = "+
linkedset.size());
linkedset.remove("D"));
System.out.println("Checking if A is present="+
linkedset.contains("A"));
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
// 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>();
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
Output:
2. Removing the Elements: The values can be removed from the LinkedHashSet using
the remove() method.
• Java
// 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>();
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
hs.add("A");
hs.add("B");
hs.add("Z");
hs.remove("B");
System.out.println(hs.remove("AC"));
Output:
Initial HashSet [Geek, For, Geeks, A, B, Z]
false
• Java
import java.io.*;
import java.util.*;
class IteratingLinkedHashSet {
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.println();
//Object
System.out.println();
Output:
Methods of LinkedHashSet
METHOD DESCRIPTION
spliterator() Creates a late-binding and fail-fast Spliterator over the elements in this set.
METHOD DESCRIPTION
equals(Object o) Compares the specified object with this set for equality.
removeAll(Collection Removes from this set all of its elements that are contained in the
c) specified collection (optional operation).
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).
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
METHOD DESCRIPTION
add(E e) Adds the specified element to this set if it is not already present.
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.
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.
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 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
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.
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
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.
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.
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.
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.
Constructor Description
TreeSet(Collection<? extends It is used to build a new tree set that contains the
E> c) elements of the collection c.
Method Description
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
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:
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
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:
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]
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:
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
importjava.util.*;
publicclassMain
publicstaticvoidmain(String[] args)
Date d1 = newDate();
Date d2 = newDate(2323223232L);
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.
importjava.util.*;
publicclassMain
publicstaticvoidmain(String[] args)
// Creating date
booleanb = d3.before(d2);
intc = d1.compareTo(d2);
System.out.println(c);
d2.setTime(204587433443L);
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
importjava.util.*;
publicclassCalendar1 {
publicstaticvoidmain(String args[])
{
Calendar c = Calendar.getInstance();
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.
// of Calendar class
importjava.util.*;
publicclassCalendar2 {
publicstaticvoidmain(String[] args)
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.
// of Calendar class
importjava.util.*;
publicclassCalendar3 {
publicstaticvoidmain(String[] args)
intmax = calendar.getMaximum(Calendar.DAY_OF_WEEK);
max = calendar.getMaximum(Calendar.WEEK_OF_YEAR);
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.
// of Calendar class
importjava.util.*;
publicclassCalendar4 {
publicstaticvoidmain(String[] args)
intmin = calendar.getMinimum(Calendar.DAY_OF_WEEK);
min = calendar.getMinimum(Calendar.WEEK_OF_YEAR);
Output:
Minimum number of days in week: 1
Minimum number of weeks in year: 1
Program 4: Java program to demonstrate add() method.
// of Calendar class
importjava.util.*;
publicclassCalendar5 {
publicstaticvoidmain(String[] args)
calendar.add(Calendar.DATE, -15);
calendar.add(Calendar.MONTH, 4);
calendar.add(Calendar.YEAR, 2);
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
class:*/
importjava.util.*;
publicclassNewClass
publicstaticvoidmain(String args[])
StringTokenizer st1 =
while(st1.hasMoreTokens())
System.out.println(st1.nextToken());
System.out.println("Using Constructor 2 - ");
StringTokenizer st2 =
while(st2.hasMoreTokens())
System.out.println(st2.nextToken());
StringTokenizer st3 =
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
1 StringTokenizer(String str)
This constructor a string tokenizer for the specified string.
Class methods
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.
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.
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 −
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.
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.
11 booleanget(int index)
Returns the current state of the bit at the specified index.
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.
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.
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);
// 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);
}
}
Output
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
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.
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 −
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.
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.
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.
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.
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);
// 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);
}
}
Output
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}