Java Unit IV
Java Unit IV
Java Unit IV
A Collection in Java is a group of Individual objects known as its elements into a single entity.
The Collections in Java provides an architecture to store and manipulate the group of objects, interfaces and
classes. This java collection is a framework.
piggy bank :- piggy bank is called a Collection and the coins are nothing but objects. Technically, a collection is
an object or a container that stores a group of other objects.
The Java collections framework provides a set of interfaces and classes to implement various data structures and
algorithms. Collection framework is present in package java. util. package. It was defined in JDK 1.2 version
which is one of the most used frameworks to date.
The Collection framework is a unified architecture for storing and manipulating a group of objects.
In Java, the Collections Framework is a hierarchy of interfaces and classes that provides easy management of a
group of objects.
The Java collections framework provides various interfaces. These interfaces include several methods to perform
different operations on collections.
Class: A class is a collection of similar types of objects. It is an implementation of the collection interface.
Interface: An interface is the abstract data type. It is at the topmost position in the framework hierarchy.
extends: It is a keyword that is used to develop inheritance between two classes and two interfaces. Inheritance in
Java refers to the concept that one can create new classes that are built upon existing classes.
implements: implements is also a keyword used to develop inheritance between class and interface. A class
implements an interface.
The Collection interface is the root interface of the collections framework hierarchy.
Java does not provide direct implementations of the Collection interface but provides implementations of its sub
interfaces like List, Set, and Queue.
It provides basic operations like adding, removing, clearing the elements in a collection, checking whether the
collection is empty, etc.
The Collection interface includes sub interfaces that are implemented by Java classes.
All the methods of the Collection interface are also present in its sub interfaces.
a) List Interface
The List interface is an ordered collection that allows us to add and remove elements like an array.
b) Set Interface
The Set interface allows us to store elements in different sets similar to the set in mathematics. It cannot have
duplicate elements.
c) Queue Interface
The Queue interface is used when we want to store and access elements in First In, First Out manner.
In Java, the Map interface allows elements to be stored in key/value pairs. Keys are unique names that can be used
to access a particular element in a map.
In Java, the Iterator interface provides methods that can be used to access elements of collections.
public void remove()- It removes the current element from the collection.
public boolean hasNext()- It returns true if there are more elements in the collection. Else, returns false.
Java collection framework consists of various classes that are used to store objects. These classes on the
top implements the Collection interface.
Java List
The List interface is a child interface of the Collection interface. The List interface is available inside
the java.util package. It defines the methods that are commonly used by classes like ArrayList, LinkedList,
Vector, and Stack.
There are three classes implemented by the list interface and they are given below.
Syntax
List<Data-Type>linkedlist= new LinkedList<Data-Type>();
Before using Array List, we need to import the java.util. Array List package first.
we have used Integer not int. It is because we cannot use primitive types while creating an arraylist. Instead, we
have to use the corresponding wrapper classes.
The ArrayList class provides various methods to perform different operations on arraylists.
1. Add elements
2. Access elements
3. Change elements
4. Remove elements
To add a single element to the arraylist, we use the add() method of the ArrayList class.
import java.util.ArrayList;
class Main
languages.add("C");
languages.add("Python");
Output
Here, we have used the add() method to add elements to the arraylist.
To access an element from the arraylist, we use the get() method of the ArrayList class.
import java.util.ArrayList;
class Main
animals.add("Dog");
animals.add("Cow");
}
}
Output
To change elements of the arraylist, we use the set() method of the ArrayList class.
import java.util.ArrayList;
class Main
languages.add("Java");
languages.add("Kotlin");
languages.add("C++");
languages.set(2, "JavaScript");
Output
To remove an element from the arraylist, we can use the remove() method of the ArrayList class.
import java.util.ArrayList;
class Main
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
}}
Output
Methods Descriptions
clone() Creates a new arraylist with the same element, size, and capacity.
contains() Searches the arraylist for the specified element and returns a boolean result.
indexOf() Searches a specified element in an arraylist and returns the index of the element.
LinkedList
Prev - stores an address of the previous element in the list. It is null for the first element
Next - stores an address of the next element in the list. It is null for the last element
Example:
import java.util.LinkedList;
class Main
animals.add("Cat");
animals.add("Cow");
LinkedList provides various methods that allow us to perform different operations in linked lists.
We can use the add() method to add an element (node) at the end of the LinkedList.
import java.util.LinkedList;
class Main {
// create linkedlist
animals.add("Dog");
animals.add("Cat");
animals.add("Cow");
animals.add(1, "Horse");
Output
The get() method of the LinkedList class is used to access an element from the LinkedList.
import java.util.LinkedList;
class Main
{
languages.add("Python");
languages.add("Java");
languages.add("JavaScript");
Output
The set() method of LinkedList class is used to change elements of the LinkedList.
import java.util.LinkedList;
class Main {
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.add("Java");
languages.set(3, "Kotlin");
}}
Output
The remove() method of the LinkedList class is used to remove an element from the LinkedList.
import java.util.LinkedList;
class Main
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.add("Kotlin");
Creating a Vector
Example:
import java.util.Vector;
class Main {
mammals.add("Dog");
mammals.add("Horse");
mammals.add(2, "Cat");
// Using addAll()
animals.add("Crocodile");
animals.addAll(mammals);
Output
Example:
import java.util.Iterator;
import java.util.Vector;
class Main {
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");
// Using get()
// Using iterator()
System.out.print("Vector: ");
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
Output
Example:
import java.util.Vector;
class Main {
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");
// Using remove()
// Using clear()
animals.clear();
Output
Creating a Stack
Stack Methods
Since Stack extends the Vector class, it inherits all the methods Vector.
i) push() Method
To add an element to the top of the stack, we use the push() method.
import java.util.Stack;
class Main {
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
Output
To remove an element from the top of the stack, we use the pop() method.
import java.util.Stack;
class Main {
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
Output
The peek() method returns an object from the top of the stack.
import java.util.Stack;
class Main {
public static void main(String[] args) {
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
Output
To search an element in the stack, we use the search() method. It returns the position of the element from
the top of the stack.
import java.util.Stack;
class Main {
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
// Search an element
Output
Position of Horse: 2
v) empty() Method
import java.util.Stack;
class Main {
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
Output
SET INTERFACE:
It extends the Collection interface.
These classes are defined in the Collections framework and implement the Set interface.
Hash Set
Linked Hash Set
Sorted Set
Tree Set
Sorted Set
Navigable Set
METHODS OF SET
The Set interface includes all the methods of the Collection interface. It's because Collection is a super interface
of Set.
addAll() - adds all the elements of the specified collection to the set
iterator() - returns an iterator that can be used to access elements of the set sequentially
removeAll() - removes all the elements from the set that is present in another specified set
retainAll() - retains all the elements in the set that are also present in another specified set
containsAll() - returns true if the set contains all the elements of the specified collection
hashCode() - returns a hash code value (address of the element in the set)
Set Operations
Union
Intersection
Subset
HASHSET
The HashSet is used to create hash table for storing set of elements.
Creating a HashSet
In order to create a hash set, we must import the java.util.HashSet package first.
Once we import the package, here is how we can create hash sets in Java.
loadFactor - The load factor of this hash set is 0.6. whenever our hash set is filled by 60%, the elements are
moved to a new hash table of double the size of the original hash table.
Methods of HashSet
The HashSet class provides various methods that allow us to perform various operations on the set.
addAll() - inserts all the elements of the specified collection to the set
import java.util.HashSet;
class Main
evenNumber.add(2);
evenNumber.add(4);
evenNumber.add(6);
numbers.addAll(evenNumber);
numbers.add(5);
}}
Output
HashSet: [2, 4, 6]
To access the elements of a hash set, we can use the iterator() method. In order to use this method, we
must import the java.util.Iterator package.
import java.util.HashSet;
import java.util.Iterator;
class Main
numbers.add(2);
numbers.add(5);
numbers.add(6);
// Accessing elements
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
} }}
Output
HashSet: [2, 5, 6]
Remove Elements
import java.util.HashSet;
class Main
numbers.add(5);
numbers.add(6);
}}
Output
HashSet: [2, 5, 6]
Is 5 removed? true
TREESET CLASS
The TreeSet does not allows to store duplicate data values, but null values are allowed.
Creating a TreeSet
In order to create a tree set, we must import the java.util.TreeSet package first.
The TreeSet class provides various methods that allow us to perform various operations on the set.
Insert Elements to TreeSet
addAll() - inserts all the elements of the specified collection to the set
import java.util.TreeSet;
class Main
evenNumbers.add(2);
evenNumbers.add(4);
evenNumbers.add(6);
numbers.add(1);
numbers.addAll(evenNumbers);
}}
Output
TreeSet: [2, 4, 6]
To access the elements of a tree set, we can use the iterator() method. In order to use this method, we
must import java.util.Iterator package. For example,
import java.util.TreeSet;
import java.util.Iterator;
class Main
{
numbers.add(2);
numbers.add(5);
numbers.add(6);
// Accessing elements
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
} }}
Output
TreeSet: [2, 5, 6]
Remove Elements
import java.util.TreeSet;
class Main
numbers.add(2);
numbers.add(5);
numbers.add(6);
Output
TreeSet: [2, 5, 6]
Is 5 removed? true
QUEUE INTERFACE
Methods of Queue
offer() - Inserts the specified element into the queue.returns true on success and false on failure.
peek() - Returns the head of the queue. Returns null if the queue is empty.
poll() - Returns and removes the head of the queue. Returns null if the queue is empty.
import java.util.Queue;
import java.util.LinkedList;
class Main {
numbers.offer(1);
numbers.offer(2);
numbers.offer(3);
}}
Output
Queue: [1, 2, 3]
Accessed Element: 1
Removed Element: 1
Updated Queue: [2, 3]
PRIORITYQUEUE
The PriorityQueue class provides the functionality of the heap data structure.
The PriorityQueue allows to store duplicate data values, but not null values.
Creating PriorityQueue
The head of the priority queue is the smallest element of the queue. And elements are removed in ascending order
from the queue.
Methods of PriorityQueue
import java.util.PriorityQueue;
class Main
numbers.offer(5);
numbers.offer(1);
numbers.offer(2);
}}
Output
Queue: [1, 5, 2]
Accessed Element: 1
Removed Element: 1
ARRAY DEQUE
Deque stands for Double-Ended Queue. A Queue is a simple, linear data structure that allows us to insert
elements from one end and remove them from another end.
The ArrayDeque class in Java provides a dynamic array that can be used as a Deque. This class implements the
Deque and the Queue interface.
It uses two pointers called head and tail. The head takes care of insertion and deletion from the front, and the tail
takes care of insertion and deletion from the end.
If an element is added at the front, then the head moves forward(from left to right). If an element is removed from
the front then the head moves backward.
If an element is added at the end, then the tail moves from right to left. If an element is removed from the end,
then the tail moves forward(left to right).
The Array Deque allows to store duplicate data values, but not null values.
Methods of ArrayDeque
The ArrayDeque class provides implementations for all the methods present in Queue and Deque interface.
We can use the offerLast() or the addLast() methods to insert elements at the rear of the ArrayDeque.
import java.util.ArrayDeque;
import java.util.Deque;
deck.addFirst(5);
deck.addFirst(10);
deck.offerFirst(15);
deck.offerFirst(20);
}}
Output:
import java.util.ArrayDeque;
import java.util.Deque;
deck.addLast(5);
deck.addLast(10);
deck.offerLast(15);
deck.offerLast(20);
}}
peekFirst() - returns the first element of the array deque (equivalent to peek())
import java.util.ArrayDeque;
class Main {
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
// Using peek()
// Using peekFirst()
// Using peekLast
}}
Output
We have the pollFirst() and the removeFirst() methods that can remove elements from the front of the
ArrayDeque that return the element present at the head or the front of the Deque.
Similarly, the pollLast() and the removeLast() methods are used to remove the last element of the Deque.
import java.util.ArrayDeque;
import java.util.Deque;
deck.addLast(5);
deck.addLast(10);
deck.addLast(15);
deck.addLast(20);
Integer i1 = deck.removeLast();
Integer i2 = deck.pollLast();
}}
Output:
To remove all the elements from the array deque, we use the clear() method.
import java.util.ArrayDeque;
class Main
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
// Using clear()
animals.clear();
}}
iterator() - returns an iterator that can be used to iterate over the array deque
descendingIterator() - returns an iterator that can be used to iterate over the array deque in reverse order
import java.util.ArrayDeque;
import java.util.Iterator;
class Main {
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
System.out.print("ArrayDeque: ");
// Using iterator()
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
// Using descendingIterator()
while(desIterate.hasNext()) {
System.out.print(desIterate.next());
System.out.print(", ");
} }}
Output
The Map interface of the Java collections framework provides the functionality of the map data structure.
The Map does not allows duplicate keys, but allows duplicate values.
These classes are defined in the collections framework and implement the Map interface.
HashMap
EnumMap
LinkedHashMap
WeakHashMap
TreeMap
SortedMap
NavigableMap
MAP INTERFACE METHODS
The Map interface includes all the methods of the Collection interface. It is because Collection is a super interface
of Map.
put(K, V) - Inserts the association of a key K and a value V into the map. If the key is already present, the new
value replaces the old value.
putAll() - Inserts all the entries from the specified map to this map.
get(K) - Returns the value associated with the specified key K. If the key is not found, it returns null
replace(K, V) - Replace the value of the key K with the new specified value V.
replace(K, oldValue, newValue) - Replaces the value of the key K with the new value newValue only if the
key K is associated with the value oldValue.
remove(K) - Removes the entry from the map represented by the key K.
remove(K, V) - Removes the entry from the map that has key K associated with value V.
HashMap
The HashMap class of the Java collections framework provides the functionality of the hash table data structure.
It stores elements in key/value pairs. Here, keys are unique identifiers used to associate each value on a map.
Create a HashMap
In order to create a hash map, we must import the java.util.HashMap package first.
In the above code, we have created a hashmap named numbers. Here, K represents the key type and V represents
the type of values. For example,
HashMap<String, Integer> numbers = new HashMap<>();
Here, the type of keys is String and the type of values is Integer.
import java.util.HashMap;
class Main {
// create a hashmap
languages.put("Java", 8);
languages.put("JavaScript", 1);
languages.put("Python", 3);
}}
Output
Here, we have used the put() method to add elements to the hashmap.
The HashMap class provides various methods to perform different operations on hashmaps.
Add elements
Access elements
Change elements
Remove elements
To add a single element to the hashmap, we use the put() method of the HashMap class.
import java.util.HashMap;
class Main {
// create a hashmap
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
}}
Output
Initial HashMap: {}
Here, we are passing the String value One as the key and Integer value 1 as the value to the put() method.
We can use the get() method to access the value from the hashmap.
import java.util.HashMap;
class Main
languages.put(1, "Java");
languages.put(2, "Python");
languages.put(3, "JavaScript");
}}
Output
We can use the replace() method to change the value associated with a key in a hashmap.
import java.util.HashMap;
class Main {
languages.put(1, "Java");
languages.put(2, "Python");
languages.put(3, "JavaScript");
languages.replace(2, "C++");
}}
Output:
import java.util.HashMap;
class Main {
languages.put(1, "Java");
languages.put(2, "Python");
languages.put(3, "JavaScript");
System.out.println("HashMap: " + languages);
}}
Output:
JAVA ENUMMAP
The EnumMap class of the Java collections framework provides a map implementation for elements of an enum.
In EnumMap, enum elements are used as keys. It implements the Map interface.
Creating an EnumMap
In order to create an enum map, we must import the java.util.EnumMap package first.
enum Size {
Here,
Integer - values of the enum map associated with the corresponding keys
Methods of EnumMap
The EnumMap class provides methods that allow us to perform various elements on the enum maps.
put() - inserts the specified key/value mapping (entry) to the enum map
putAll() - inserts all the entries of a specified map to this map
import java.util.EnumMap;
class Main {
enum Size {
sizes1.put(Size.SMALL, 28);
sizes1.put(Size.MEDIUM, 32);
sizes2.putAll(sizes1);
sizes2.put(Size.LARGE, 36);
}}
Output
In the above example, we have used the putAll() method to insert all the elements of an enum map sizes1 to an
enum map of sizes2.
entrySet() - returns a set of all the keys/values mapping (entry) of an enum map
class Main {
enum Size {
sizes.put(Size.SMALL, 28);
sizes.put(Size.MEDIUM, 32);
sizes.put(Size.LARGE, 36);
sizes.put(Size.EXTRALARGE, 40);
}}
Output
The get() method returns the value associated with the specified key. It returns null if the specified key is not
found.
import java.util.EnumMap;
class Main {
enum Size {
sizes.put(Size.SMALL, 28);
sizes.put(Size.MEDIUM, 32);
sizes.put(Size.LARGE, 36);
sizes.put(Size.EXTRALARGE, 40);
}}
Output
Value of MEDIUM: 32
remove(key) - returns and removes the entry associated with the specified key from the map
remove(key, value) - removes the entry from the map only if the specified key mapped to the specified value and
return a boolean value
import java.util.EnumMap;
class Main {
enum Size {
sizes.put(Size.MEDIUM, 32);
sizes.put(Size.LARGE, 36);
sizes.put(Size.EXTRALARGE, 40);
}}
Output
Removed Value: 32
JAVA TREEMAP
The TreeMap class that implements treemap in Java is a part of java.util package. It implements the Map
interface.
The TreeMap class extends AbstractMap class and also implements the NavigableMap and SortedMap
(indirectly) interface.
we have created a TreeMap named numbers without any arguments. In this case, the elements in TreeMap are
sorted naturally (ascending order).
Methods of TreeMap
The TreeMap class provides various methods that allow us to perform operations on the map.
putAll() - inserts all the entries from specified map to this map
putIfAbsent() - inserts the specified key/value mapping to the map if the specified key is not present in the map
import java.util.TreeMap;
class Main {
// Using put()
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);
// Using putIfAbsent()
evenNumbers.putIfAbsent("Six", 6);
numbers.put("One", 1);
// Using putAll()
numbers.putAll(evenNumbers);
}}
Output
import java.util.TreeMap;
class Main {
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
// Using entrySet()
System.out.println("Key/Value mappings: " + numbers.entrySet());
// Using keySet()
// Using values()
}}
Output
Values: [1, 3, 2]
remove(key) - returns and removes the entry associated with the specified key from a TreeMap
remove(key, value) - removes the entry from the map only if the specified key is associated with the specified
value and returns a boolean value
import java.util.TreeMap;
class Main {
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
Output
Removed value = 2
replace(key, value) - replaces the value mapped by the specified key with the new value
replace(key, old, new) - replaces the old value with the new value only if the old value is already associated with
the specified key
replaceAll(function) - replaces each value of the map with the result of the specified function
import java.util.TreeMap;
class Main {
numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
// Using replace()
numbers.replace("Second", 22);
numbers.replace("Third", 3, 33);
// Using replaceAll()
}}
Output
TreeMap Comparator
Treemap elements are sorted naturally (in ascending order). However, we can also customize the ordering
of keys.
we need to create our own comparator class based on which keys in a treemap are sorted.
import java.util.TreeMap;
import java.util.Comparator;
class Main {
numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
numbers.put("Fourth", 4);
@Override
if (value > 0) {
return -1;
return 1;
else {
return 0;
}} }}
Output
The Java collections framework provides various algorithms that can be used to manipulate elements stored in
data structures.
Algorithms in Java are static methods that can be used to perform various operations on collections.
All the collection algorithms in the java are defined in a class called Collections which defined in
the java.util package.
All these algorithms are highly efficient and make coding very easy. It is better to use them than trying to re-
implement them.
Since algorithms can be used on various collections, these are also known as generic algorithms.
Method Description
void sort(List list, Comparator comp) Sorts the elements of the list as determined by
Comparator comp.
void rotate(List list, int n) Rotates list by n places to the right. To rotate
left, use a negative value for n.
Method Description
void shuffle(List list, Random r) Shuffles the elements in the list by using r as a
source of random numbers.
void copy(List list1, List list2) Copies the elements of list2 to list1.
void swap(List list, int idx1, int idx2) Exchanges the elements in the list at the indices
specified by idx1 and idx2.
int binarySearch(List list, Object value) Returns the position of value in the list (must be
in the sorted order), or -1 if value is not found.
Object max(Collection c, Comparator Returns the largest element from the collection c
comp) as determined by Comparator comp.
Object min(Collection c, Comparator Returns the smallest element from the collection
comp) c as determined by Comparator comp.
void fill(List list, Object obj) Assigns obj to each element of the list.
Accessing a Collection
To access, modify or remove any element from any collection we need to first find the element, for which we
have to cycle throught the elements of the collection. There are three possible ways to cycle through the elements
of any collection.
import java.util.*;
class Test_Iterator
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
while(it.hasNext())
System.out.print(it.next()+" ");
} }}
Output :
ab bc cd de
ListIterator Interface is used to traverse a list in both forward and backward direction. It is available to only those
collections that implement the List Interface.
import java.util.*;
class Test_Iterator
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
System.out.print(litr.next()+" ");
System.out.print(litr.next()+" ");
} }}
Output :
ab bc cd de
de cd bc ab
for-each version of for loop can also be used for traversing each element of a collection. But this can only be used
if we don't want to modify the contents of a collection and we don't want any reverse access. for-each loop can
cycle through any collection of object that implements Iterable interface.
import java.util.*;
class ForEachDemo
ls.add("a");
ls.add("b");
ls.add("c");
ls.add("d");
{
System.out.print(str+" ");
} }}
Output :
abcd
Comparator Interface
In Java, Comparator interface is used to order the object in your own way. It gives you ability to decide how
element are stored within sorted collection and map.
Comparator Interface defines compare() method. This method compare two object and return 0 if two object are
equal. It returns a positive value if object1 is greater than object2. Otherwise a negative value is return. The
method can throw a ClassCastException if the type of object are not compatible for comparison.
Example
Student class
class Student
int roll;
String name;
Student(int r,String n)
roll = r;
name = n;
MyComparator class
This class defines the comparison logic for Student class based on their roll. Student object will be sotred in
ascending order of their roll.
{
if(s1.roll == s2.roll) return 0;
} }
System.out.println(ts);
}}
Output :
The java collection framework has a class Arrays that provides methods for creating dynamic array and perform
various operations like search, asList, campare, etc.
The Arrays class in java is defined in the java.util package. All the methods defined by Arrays class are static
methods.
int binarySearch(): The binarySearch() method is used to search the index position of an element with a specific
value.
compare(array1, array2): This method is used to compare two arrays passed as parameters lexicographically.
Both arrays array1 and array2 must have the same data types.
compareUnsigned(array1, array2): This method is used to compare two arrays lexicographically, numerically
treating elements as unsigned.
copyOf(arrayOriginal, newLength): This method was added in arrays class in Java 6 version. It returns an array
that is copy of arrayOriginal. newLength represents the length of copy.
copyOfRange(arrayOriginal, from, to): This method was also added in arrays class in Java 1.6 version. The
copyOfRange() method returns a copy of range (from one index to another) within an array.
deepEquals(): The deepEquals() method (added in arrays class in Java 5 version) returns true if the two specified
arrays are deeply equal to one another.
equals(array1, array2): The equals() method is used to check equality for one-dimensional array. It returns true
if two arrays are equivalent.
fill(array, value): The fill() method is used to fill an array with the specified value.
fill(array, from, to, value): This version of fill() method is used to assign a value to a subset of an array.
sort(array): The sort() method is used to sort the entire array in ascending order.
sort(array, from, to): This version of sort() method is used to sort elements of an array within a specific range in
ascending order.
toString(array): The toString() method is used to format elements of array in a string. Each element value is
enclosed in brackets and are separated from each other with commas.
stream(array): The stream() method was introduced in Arrays class in Java 8 version. It is used to convert an
array into a stream of corresponding data types.
stream(array, from, to): This version of stream() method is used to convert array into a stream with a specific
range.
parallelSort(array): This method is used to sort elements of an array of larger size in parallel. It can be used to
sort array of primitive types or objects.
parallelSort(array, from, to): This form of parallelSort() method is used to sort an array in a specific range.
mismatch(array1, array2): The mismatch() method finds and returns the index of the first mismatch between
two arrays.
mismatch(array1, from, to, array2, from, to): This form of mismatch() method finds and returns the relative
index of the first mismatch between two arrays over the specified range.
hashCode(array): This method returns a hash code based on the elements of the specified array.
Early version of java did not include the Collection framework. It only defined several classes and
interface that provide method for storing objects. When Collection framework were added in J2SE 1.2, the
original classes were reengineered to support the collection interface. These classes are also known as Legacy
classes. All legacy claases and interface were redesign by JDK 5 to support Generics.
Dictionary
HashTable
Properties
Stack
Vector
Vector class
Vector()
Vector(int size)
Vector(int size, int incr)
Vector(Collection< ? extends E> c)
Method Description
import java.util.*;
public class Test
ve.add(10);
ve.add(20);
ve.add(30);
ve.add(40);
ve.add(50);
ve.add(60);
Enumeration en = ve.elements();
while(en.hasMoreElements())
System.out.println(en.nextElement());
} }}
Output :
10
20
30
40
50
60
HASHTABLE CLASS
Like HashMap, Hashtable also stores key/value pair in hashtable. However neither keys nor values can be null.
There is one more difference between HashMap and Hashtable that is Hashtable is synchronized while HashMap
is not.
Hashtable has following four constructor
Hashtable()
Hashtable(int size)
import java.util.*;
class HashTableDemo
ht.put("a",new Integer(100));
ht.put("b",new Integer(200));
ht.put("c",new Integer(300));
ht.put("d",new Integer(400));
Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
Map.Entry m=(Map.Entry)itr.next();
System.out.println(itr.getKey()+" "+itr.getValue());
} }}
Output:
a 100
b 200
c 300
d 400
Properties class
It is used to maintain list of value in which both key and value are String
Properties()
Properties(Properties default)
import java.util.*;
} }}
Output :
The Stack class extends the Vector class, which has members that follow the LIFO (LAST IN
FIRST OUT) principle. The stack implementation only has one default constructor, Stack ().
import java.util.*;
class Coderz {
stobj.push(10);
stobj.push(9);
stobj.push(8);
stobj.push(7);
stobj.push(6);
while(eobj.hasMoreElements())
System.out.print(eobj.nextElement()+" ");
stobj.pop();
stobj.pop();
while(eobj2.hasMoreElements())
System.out.print(eobj2.nextElement()+" ");
}}
Output:
10 9 8 7 6
Dictionary Class:
The Dictionary class is similar to Map in that it represents the key/value storage repository. The Dictionary class
is an abstract class that holds data in the form of a key/value pair. The dictionary can be defined as a collection of
key/value pairs.
UTILITY CLASSES
StringTokenizer class
The StringTokenizer is a built-in class in java used to break a string into tokens. The StringTokenizer class is
available inside the java.util package.
The StringTokenizer class object internally maintains a current position within the string to be tokenized.
A token is returned by taking a substring of the string that was used to create the StringTokenizer object.
StringTokenizer(String str) - It creates StringTokenizer object for the specified string str with default delimeter.
StringTokenizer(String str, String delimeter) - It creates StringTokenizer object for the specified string str with
specified delimeter.
StringTokenizer(String str, String delimeter, boolean returnValue) - It creates StringTokenizer object with
specified string, delimeter and returnValue.
String nextToken() -It returns the next token from the StringTokenizer object.
String nextToken(String delimeter)- It returns the next token from the StringTokenizer object based on the
delimeter.
Object nextElement() - It returns the next token from the StringTokenizer object.
boolean hasMoreTokens() - It returns true if there are more tokens in the StringTokenizer object. otherwise
returns false.
boolean hasMoreElements() - It returns true if there are more tokens in the StringTokenizer object. otherwise
returns false.
BITSET CLASS:
The BitSet is a built-in class in java used to create a dynamic array of bits represented by boolean values.
The BitSet class is available inside the java.util package.
The BitSet array can increase in size as needed. This feature makes the BitSet similar to a Vector of bits.
The bit values can be accessed by non-negative integers as an index.
The size of the array is flexible and can grow to accommodate additional bit as needed.
The default value of the BitSet is boolean false with a representation as 0 (off).
BitSet uses 1 bit of memory per each boolean value.
BitSet(int noOfBits) - It creates a BitSet object with number of bits that it can hold. All bits are initialized to
zero.
void and(BitSet bitSet) - It performs AND operation on the contents of the invoking BitSet object with those
specified by bitSet.
void andNot(BitSet bitSet) - For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared.
void or(BitSet bitSet) - It performs OR operation on the contents of the invoking BitSet object with those
specified by bitSet.
void xor(BitSet bitSet) - It performs XOR operation on the contents of the invoking BitSet object with those
specified by bitSet.
void clear( ) - It sets all the bits to zeros of the invoking BitSet.
void clear(int index) - It set the bit specified by given index to zero.
boolean equals(Object bitSet) - It retruns true if both invoking and argumented BitSets are equal, otherwise
returns false.
int length( ) - It returns the total number of bits in the invoking BitSet.
String toString( ) - It returns the string equivalent of the invoking BitSet object.
DATE CLASS
The Date is a built-in class in java used to work with date and time in java. The Date class is available inside
the java.util package. The Date class represents the date and time with millisecond precision.
Date( ) - It creates a Date object that represents current date and time.
Date(long milliseconds) - It creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.
Date(int year, int month, int date) - It creates a date object with the specified year, month, and date.
Date(int year, int month, int date, int hrs, int min) - It creates a date object with the specified year, month, date,
hours, and minuts.
Date(int year, int month, int date, int hrs, int min, int sec) - It creates a date object with the specified year, month,
date, hours, minuts and seconds.
Date(String s) - It creates a Date object and initializes it so that it represents the date and time indicated by the
string s, which is interpreted as if by the parse(java.lang.String) method.
boolean after(Date date) - It returns true, if the invoking date is after the argumented date.
boolean before(Date date) - It returns true, if the invoking date is before the argumented date.
Date from(Instant instant) - It returns an instance of Date object from Instant date.
void setTime(long time) - It changes the current date and time to given time.
boolean equals(Date date) - It compares current date with given date for equality.
CALENDAR CLASS
The Calendar is a built-in abstract class in java used to convert date between a specific instant in time and a set of
calendar fields such as MONTH, YEAR, HOUR, etc. The Calendar class is available inside the java.util package.
As the Calendar class is an abstract class, we can not create an object using it.
We will use the static method Calendar.getInstance() to instantiate and implement a sub-class.
Date getTime() - It returns a Date object representing the invoking Calendar's time value.
TimeZone getTimeZone() - It returns the time zone object associated with the invoking calendar.
void setTimeZone(TimeZone value) - It sets the TimeZone with passed TimeZone value.
RANDOM CLASS
The Random is a built-in class in java used to generate a stream of pseudo-random numbers in java programming.
The Random class provides several methods to generate random numbers of type integer, double, long, float etc.
Random number generation algorithm works on the seed value. If not provided, seed value is created from system
nano time.
Random(long seedValue) - It creates a new random number generator using a single long seedValue.
FORMATTER CLASS
The Formatter is a built-in class in java used for layout justification and alignment, common formats for numeric,
string, and date/time data, and locale-specific output in java programming. The Formatter class is defined as final
class inside the java.util package.
Formatter(String fileName) - It creates a new formatter with the specified file name.
SCANNER CLASS:
The Scanner is a built-in class in java used for read the input from the user in java programming. The Scanner
class is defined inside the java.util package.
The Scanner class provides the easiest way to read input in a Java program.
The Scanner object breaks its input into tokens using a delimiter pattern, the default delimiter is whitespace.
Scanner(InputStream source) - It creates a new Scanner that produces values read from the specified input
stream.
Scanner(File source) - It creates a new Scanner that produces values scanned from the specified file.
Scanner(String source) - It creates a new Scanner that produces values scanned from the specified string.
Scanner(Readable source) - It creates a new Scanner that produces values scanned from the specified source.