Introduction to Collections
A collection sometimes called a container is simply an object that
groups multiple elements into a single unit. Collections are used to store,
retrieve, manipulate, and communicate aggregate data. Typically, they
represent data items that form a natural group, such as a poker hand (a
collection of cards), a mail folder (a collection of letters), or a telephone
directory (a mapping of names to phone numbers).
What Is a Collections Framework?
A collections framework is a unified architecture for representing and
manipulating collections. All collections frameworks contain the following:
Interfaces: These are abstract data types that represent
collections. Interfaces allow collections to be manipulated
independently of the details of their representation. In objectoriented languages, interfaces generally form a hierarchy.
Implementations (ie. Classes): These are the concrete
implementations of the collection interfaces. In essence, they are
reusable data structures.
Algorithms: These are the methods that perform useful
computations, such as searching and sorting, on objects that
implement collection interfaces. The algorithms are said to
be polymorphic: that is, the same method can be used on many
different implementations of the appropriate collection interface. In
essence, algorithms are reusable functionality.
Benefits of the Java Collections Framework
The Java Collections Framework provides the following benefits:
Reduces programming effort: By providing useful data structures and
algorithms, the Collections Framework frees you to concentrate on the
important parts of your program rather than on the low-level "plumbing"
required to make it work. By facilitating interoperability among unrelated APIs,
the Java Collections Framework frees you from writing adapter objects or
conversion code to connect APIs.
Increases program speed and quality: This Collections Framework
provides high-performance, high-quality implementations of useful data
structures and algorithms. The various implementations of each interface are
interchangeable, so programs can be easily tuned by switching collection
implementations. Because you're freed from the drudgery of writing your own
data structures, you'll have more time to devote to improving programs' quality
and performance.
Allows interoperability among unrelated APIs: The collection interfaces
are the vernacular by which APIs pass collections back and forth. If my
network administration API furnishes a collection of node names and if your
GUI toolkit expects a collection of column headings, our APIs will interoperate
seamlessly, even though they were written independently.
Reduces effort to learn and to use new APIs: Many APIs naturally take
collections on input and furnish them as output. In the past, each such API
had a small sub-API devoted to manipulating its collections. There was little
consistency among these ad hoc collections sub-APIs, so you had to learn
each one from scratch, and it was easy to make mistakes when using them.
With the advent of standard collection interfaces, the problem went away.
Reduces effort to design new APIs: This is the flip side of the previous
advantage. Designers and implementers don't have to reinvent the wheel
each time they create an API that relies on collections; instead, they can use
standard collection interfaces.
Fosters software reuse: New data structures that conform to the standard
collection interfaces are by nature reusable. The same goes for new
algorithms that operate on objects that implement these interfaces.
So What Do You Do with a Collection?
There are a few basic operations you'll normally use with collections:
Add objects to the collection.
Remove objects from the collection.
Find out if an object (or group of objects) is in the collection.
Retrieve an object from the collection (without removing it).
Iterate through the collection, looking at each element (object) one after another.
Hierarchy of Collection Framework
Let us see the hierarchy of collection [Link] [Link] package contains all the classes and
interfaces for Collection framework.
Purple colored : Classes
Green colored : Interface
OR
Interfaces
The Collection Interface
This enables you to work with groups of objects; it is at the top of the
collections hierarchy.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
No.
Method
Description
public boolean add(Object element)
is used to insert an element in this collection.
public boolean addAll(Collection c)
is used to insert the specified collection elements in the invoking
collection.
public
boolean
remove(Object
is used to delete an element from this collection.
element)
4
5
public boolean removeAll(Collection
is used to delete all the elements of specified collection from the
c)
invoking collection.
public boolean retainAll(Collection c)
is used to delete all the elements of invoking collection except the
specified collection.
public int size()
return the total number of elements in the collection.
public void clear()
removes the total no of element from the collection.
public
boolean
contains(Object
is used to search an element.
element)
9
public boolean containsAll(Collection
is used to search the specified collection in this collection.
c)
1
public Iterator iterator()
returns an iterator.
public Object[] toArray()
converts collection into array.
public boolean isEmpty()
checks if collection is empty.
public
matches two collection.
element)
public int hashCode()
0
1
1
1
2
boolean
equals(Object
returns the hashcode number for collection.
Not all collections in the Collections Framework actually implement the Collection
interface. In other words, not all collections pass the IS-A test for Collection.
Specifically, none of the Map-related classes and interfaces extend from Collection.
So while SortedMap, Hashtable, HashMap, TreeMap, and LinkedHashMap are all
thought of as collections, none are actually extended from Collection.
Three overloaded uses of the word "collection":
collection (lowercase c), which represents any of the data structures in which
objects are stored and iterated over.
Collection (capital C), which is actually the [Link] interface from which
Set, List, and Queue extend. (That's right, extend, not implement. There are no direct
implementations of Collection.)
Collections (capital C and ends with s) is the [Link] class that holds a
pile of static utility methods for use with collections.
The List Interface
This extends Collection and an instance of List stores an ordered collection of
elements.
A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate
elements. Elements can be inserted or accessed by their position in the list, using a zerobased index.
ArrayList
LinkedList
Vector
2.A)
Java ArrayList class
o Java ArrayList class uses a dynamic array for storing the [Link] extends
AbstractList class and implements List interface.
o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to
be occurred if any element is removed from the array list.
ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist
In generic collection, we specify the type in angular braces. Now ArrayList
is forced to have only specified type of objects in it. If you try to add
another type of object, it gives compile time error.
Example of Java ArrayList class
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
import [Link].*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();//creating arraylist
[Link]("Ravi");//adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator itr=[Link]();//getting Iterator from arraylist to traverse elements
while([Link]()){
[Link]([Link]());
}
}
}
Or (Iterating through for:each loop// Replacement of lines 11-14)
1.
2.
for(String obj:al)
[Link](obj);
O/P :
Ravi
Vijay
Ravi
Ajay
1.
2.
3.
4.
5.
6.
Example of addAll(Collection c) method
import [Link].*;
class TestCollection4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
[Link]("Ravi");
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
[Link]("Vijay");
[Link]("Ajay");
ArrayList<String> al2=new ArrayList<String>();
[Link]("Sonoo");
[Link]("Hanumat");
[Link](al2);
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
O/P :
Ravi
Vijay
Ajay
Sonoo
Hanumat
Example of removeAll() method
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
import [Link].*;
class TestCollection5{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
ArrayList<String> al2=new ArrayList<String>();
[Link]("Ravi");
[Link]("Hanumat");
[Link](al2);
[Link]("iterating the elements after removing the elements of al2...");
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
O/P :
iterating the elements after removing the elements of al2...
Vijay
Ajay
Example of retainAll() method
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
import [Link].*;
class TestCollection6{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
ArrayList<String> al2=new ArrayList<String>();
[Link]("Ravi");
[Link]("Hanumat");
[Link](al2);
[Link]("iterating the elements after retaining the elements of al2...");
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
O/P:
iterating the elements after retaining the elements of al2...
Ravi
2.B)
Java LinkedList class
Java LinkedList class uses doubly linked list to store the elements. It extends the
AbstractList class and implements List and Deque interfaces.
Java LinkedList class can contain duplicate elements.
Java LinkedList class maintains insertion order.
Java LinkedList class is non synchronized.
In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
Java LinkedList class can be used as list, stack or queue.
Java LinkedList Example
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
import [Link].*;
public class TestCollection7{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
O/P:
Ravi
Vijay
Ravi
Ajay
Difference between ArrayList and LinkedList
ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non
synchronized classes.
But there are many differences between ArrayList and LinkedList classes that are given below.
ArrayList
LinkedList
1) ArrayList internally uses dynamic array to store the
LinkedList internally uses doubly linked list to store
elements.
the elements.
2) Manipulation with ArrayList is slow because it internally
Manipulation with LinkedList is faster than ArrayList
uses array. If any element is removed from the array, all the
because it uses doubly linked list so no bit shifting is
bits are shifted in memory.
required in memory.
3)
ArrayList
class
can act
as
list only
because
it
LinkedList class can act as a list and queue both
implements List only.
because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data.
LinkedList is better for manipulating data.
2.C)
Java Vector class
The Vector class implements a growable array of objects. Similar to array, elements of
Vector can be accessed using an integer index. However, the size of a Vector can grow or
shrink as needed to accommodate adding and removing items after the Vector has been
created.
Vector is synchronized which means it is suitable for thread-safe operations but it gives
poor performance when used in multi-thread environment. It is recommended to use
ArrayList (it is non-synchronized, gives good performance) in place of Vector when there
is no need of thread-safe operations.
Example of Java Vector
Let's see a simple example of java Vector class that uses Enumeration interface.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
import [Link].*;
class TestVector1{
public static void main(String args[]){
Vector<String> v=new Vector<String>();//creating vector
[Link]("umesh");//method of Collection
[Link]("irfan");//method of Vector
[Link]("kumar");
//traversing elements using Enumeration
Enumeration e=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Output:
umesh
irfan
kumar
Eg2)
import [Link].*;
public class VectorExample {
public static void main(String args[]) {
/* Vector of initial capacity(size) of 2 */
Vector<String> vec = new Vector<String>(2);
/* Adding elements to a vector*/
[Link]("Apple");
[Link]("Orange");
[Link]("Mango");
[Link]("Fig");
/* check size and capacityIncrement*/
[Link]("Size is: "+[Link]());
[Link]("Default capacity increment is: "+[Link]());
[Link]("fruit1");
[Link]("fruit2");
[Link]("fruit3");
/*size and capacityIncrement after two insertions*/
[Link]("Size after addition: "+[Link]());
[Link]("Capacity after increment is: "+[Link]());
/*Display Vector elements*/
Enumeration en = [Link]();
[Link]("\nElements are:");
while([Link]())
[Link]([Link]() + " ");
}
}
Size is: 4
Default capacity increment is: 4
Size after addition: 7
Capacity after increment is: 8
[Initial Capacity:2]
Elements are:
Apple Orange Mango Fig fruit1 fruit2 fruit3
Vector increments 100% means doubles the array size if total number of element exceeds than
its capacity
Difference between ArrayList and Vector
ArrayList and Vector both implements List interface and maintains insertion order.
But there are many differences between ArrayList and Vector classes that are given
below.
ArrayList
Vector
1) ArrayList is not synchronized.
2)
ArrayList increments
50% of
Vector is synchronized.
current
Vector increments 100% means doubles the array
array size if number of element exceeds from
size if total number of element exceeds than its
its capacity.
capacity.
3) ArrayList is not a legacy class,
it
is
Vector is a legacy class.
introduced in JDK 1.2.
4)
ArrayList
is fast because
it
is
non-
synchronized.
Vector is slow because it is synchronized i.e. in
multithreading environment, it will hold the other
threads in runnable or non-runnable state until
current thread releases the lock of object.
5)
ArrayList
uses Iterator interface
traverse the elements.
The Set
to
Vector uses Enumeration interface to traverse the
elements. But it can use Iterator also.
This extends Collection to handle sets, which must contain unique elements
A Set is a Collection that cannot contain duplicate elements. There are three main
implementations of Set interface: HashSet, TreeSet, and LinkedHashSet. HashSet, which
stores its elements in a hash table, is the best-performing implementation; however it
makes no guarantees concerning the order of iteration. TreeSet, which stores its elements
in a red-black tree, orders its elements based on their values; it is substantially slower
than HashSet. LinkedHashSet, which is implemented as a hash table with a linked list
running through it, orders its elements based on the order in which they were inserted
into the set (insertion-order).
HashSet
LinkedHashSet
TreeSet
3.A)
Java HashSet class
uses hashtable to store the [Link] extends AbstractSet class and implements Set
interface.
contains unique elements only.
It makes no guarantees as to the iteration order of the set; in particular, it does not
guarantee that the order will remain constant over time. This class permits the null
element. This class is not synchronized. However it can be synchronized explicitly like
this: Set s = [Link](new HashSet(...));
Points to Note about HashSet:
1.
HashSet doesnt maintain any order, the elements would be returned in any random
order.
2.
HashSet doesnt allow duplicates. If you try to add a duplicate element in HashSet,
the old value would be overwritten.
3.
HashSet allows null values however if you insert more than one nulls it would still
return only one null value.
4.
HashSet is non-synchronized.
5.
The iterator returned by this class is fail-fast which means iterator would
throw ConcurrentModificationException if HashSet has been modified after creation of
iterator, by any means except iterators own remove method.
HashSet Example
import [Link];
public class HashSetExample {
public static void main(String args[]) {
// HashSet declaration
HashSet<String> hset =
new HashSet<String>();
// Adding elements to the HashSet
[Link]("Apple");
[Link]("Mango");
[Link]("Grapes");
[Link]("Orange");
[Link]("Fig");
//Addition of duplicate elements
[Link]("Apple");
[Link]("Mango");
//Addition of null values
[Link](null);
[Link](null);
//Displaying HashSet elements
[Link](hset);
}
}
Output:
[null, Mango, Grapes, Apple, Orange, Fig]
As you can see there all the duplicate values are not present in the output including the
duplicate null value.
3.B)
Java LinkedHashSet class:
contains unique elements only like HashSet. It extends HashSet class and implements Set
interface.
maintains insertion order.
it is similar to the HashSet and TreeSet except the below mentioned differences:
1.
HashSet doesnt maintain any kind of order of its elements.
2.
TreeSet sorts the elements in ascending order.
3.
LinkedHashSet maintains the insertion order. Elements gets sorted in the same
sequence in which they have been added to the Set.
Example of LinkedHashSet:
import [Link];
public class LinkedHashSetExample {
public static void main(String args[]) {
// LinkedHashSet of String Type
LinkedHashSet<String> lhset = new LinkedHashSet<String>();
// Adding elements to the LinkedHashSet
[Link]("Z");
[Link]("PQ");
[Link]("N");
[Link]("O");
[Link]("KK");
[Link]("FGH");
[Link](lhset);
// LinkedHashSet of Integer Type
LinkedHashSet<Integer> lhset2 = new LinkedHashSet<Integer>();
// Adding elements
[Link](99);
[Link](7);
[Link](0);
[Link](67);
[Link](89);
[Link](66);
[Link](lhset2);
}
}
Output:
[Z, PQ, N, O, KK, FGH]
[99, 7, 0, 67, 89, 66]
Observe the output: Both types of LinkedHashSet have preserved the insertion order.
Eg2)
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
import [Link].*;
class TestCollection10{
public static void main(String args[]){
LinkedHashSet<String> al=new LinkedHashSet<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]()){
13.
14.
15.
16.
[Link]([Link]());
}
}
}
Output:>Ravi
Vijay
Ajay
3.C) Java
TreeSet class
contains unique elements only like HashSet. The TreeSet class implements NavigableSet
interface that extends the SortedSet interface.
maintains ascending order.
TreeSet is similar to HashSet except that it sorts the elements in the ascending
order while HashSet doesnt maintain any order. TreeSet allows null element but
like HashSet it doesnt allow. Like most of the other collection classes this class is
also not synchronized, however it can be synchronized explicitly like
this: SortedSet s = [Link](new TreeSet(...));
TreeSet Example:
In this example we have two TreeSet (TreeSet<String> &TreeSet<Integer>). We have added
the values to both of them randomly however the result we got is sorted in ascending
order.
import [Link];
public class TreeSetExample {
public static void main(String args[]) {
// TreeSet of String Type
TreeSet<String> tset = new TreeSet<String>();
// Adding elements to TreeSet<String>
[Link]("ABC");
[Link]("String");
[Link]("Test");
[Link]("Pen");
[Link]("Ink");
[Link]("Jack");
//Displaying TreeSet
[Link](tset);
// TreeSet of Integer Type
TreeSet<Integer> tset2 = new TreeSet<Integer>();
// Adding elements to TreeSet<Integer>
[Link](88);
[Link](7);
[Link](101);
[Link](0);
[Link](3);
[Link](222);
[Link](tset2);
}
}
Output: You can see both the TreeSet have been sorted in ascending order implicitly.
[ABC, Ink, Jack, Pen, String, Test]
[0, 3, 7, 88, 101, 222]
How to convert a HashSet to a TreeSet
Program
Here is the complete code for HashSet to TreeSet conversion. We have a HashSet of Strings
and we are creating a TreeSet of strings by copying all the elements of HashSet to TreeSet.
import [Link];
import [Link];
import [Link];
class ConvertHashSettoTreeSet{
public static void main(String[] args) {
// Create a HashSet
HashSet<String> hset = new HashSet<String>();
//add elements to HashSet
[Link]("Element1");
[Link]("Element2");
[Link]("Element3");
[Link]("Element4");
// Displaying HashSet elements
[Link]("HashSet contains: "+ hset);
// Creating a TreeSet of HashSet elements
Set<String> tset = new TreeSet<String>(hset);
// Displaying TreeSet elements
[Link]("TreeSet contains: ");
for(String temp : tset){
[Link](temp);
}
}
}
Output:
HashSet contains: [Element1, Element2, Element3, Element4]
TreeSet contains:
Element1
Element2
Element3
Element4
The Map
This maps unique keys to values.
A Map is an object that maps keys to values. A map cannot contain duplicate keys. There
are three main implementations of Map interfaces: HashMap, TreeMap, and
LinkedHashMap.
HashMap: it makes no guarantees concerning the order of iteration
TreeMap: It stores its elements in a red-black tree, orders its elements based on their
values; it is substantially slower than HashMap.
LinkedHashMap: It orders its elements based on the order in which they were inserted into
the set (insertion-order).
HashMap
TreeMap
LinkedHashMap
Commonly used methods of Map interface:
1.
public Object put(Object key, Object value): is used to insert an entry in this map.
2.
public void putAll(Map map): is used to insert the specified map in this map.
3.
public Object remove(Object key): is used to delete an entry for the specified key.
4.
public Object get(Object key): is used to return the value for the specified key.
5.
public boolean containsKey(Object key): is used to search the specified key from this
map.
6.
public boolean containsValue(Object value): is used to search the specified value
from this map.
7.
public Set keySet(): returns the Set view containing all the keys.
8.
public Set entrySet(): returns the Set view containing all the keys and values.
Entry
Entry is the subinterface of Map. So we will be accessed it by [Link] name. It provides
methods to get key and value.
Methods of Entry interface:
1.
public Object getKey(): is used to obtain key.
2.
public Object getValue():is used to obtain value.
4.A)
Java HashMap class
A HashMap contains values based on the key. It implements the Map interface and extends
AbstractMap class.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
HashMap is a Map based collection class that is used for storing Key & value pairs. This
class makes no guarantees as to the order of the map. It is similar to the Hashtable class
except that it is unsynchronized and permits nulls(null values and null key).
HashMap maintains key and value pairs and often denoted as HashMap<Key, Value> or
HashMap<K, V>. HashMap implements Map interface. HashMap is similar to Hashtable with
two exceptions HashMap methods are unsynchornized and it allows null key and null
values unlike Hashtable. It is used for maintaining key and value mapping.
It is not an ordered collection which means it does not return the keys and values in the
same order in which they have been inserted into the HashMap. It neither does any kind of
sorting to the stored keys and Values. You must need to import [Link] or its
super class in order to use the HashMap class and methods.
HashMap Example in Java:
In this example we have demonstrate almost all the important methods of HashMap class.
For theoretical explanation of methods you can refer the HashMap documentation.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Details {
public static void main(String args[]) {
/* This is how to declare HashMap */
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
/*Adding elements to HashMap*/
[Link](12, "Chaitanya");
[Link](2, "Rahul");
[Link](7, "Singh");
[Link](49, "Ajeet");
[Link](3, "Anuj");
/* Display content using Iterator*/
Set set = [Link]();
Iterator iterator = [Link]();
while([Link]()) {
[Link] mentry = ([Link])[Link]();
[Link]("key is: "+ [Link]() + " & Value is: ");
[Link]([Link]());
}
Or
1.
2.
3.
for([Link] m:[Link]()){
[Link]([Link]()+" "+[Link]());
}
/* Get values based on key*/
String var= [Link](2);
[Link]("Value at index 2 is: "+var);
/* Remove values based on key*/
[Link](3);
[Link]("Map key and values after removal:");
Set set2 = [Link]();
Iterator iterator2 = [Link]();
while([Link]()) {
[Link] mentry2 = ([Link])[Link]();
[Link]("Key is: "+[Link]() + " & Value is: ");
[Link]([Link]());
}
}
}
Output:
key is: 49 & Value is: Ajeet
key is: 2 & Value is: Rahul
key is: 3 & Value is: Anuj
key is: 7 & Value is: Singh
key is: 12 & Value is: Chaitanya
Value at index 2 is: Rahul
Map key and values after removal:
Key is: 49 & Value is: Ajeet
Key is: 2 & Value is: Rahul
Key is: 7 & Value is: Singh
Key is: 12 & Value is: Chaitanya
4.B)
Java LinkedHashMap class
A LinkedHashMap contains values based on the key. It implements the Map interface and
extends HashMap class.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
LinkedHashMap is a Hash table and linked list implementation of the Map interface, with
predictable iteration order. This implementation differs from HashMap in that it maintains
a doubly-linked list running through all of its entries. This linked list defines the iteration
ordering, which is normally the order in which keys were inserted into the map (insertionorder).
HashMap doesnt maintain any order.
TreeMap sort the entries in ascending order of keys.
LinkedHashMap maintains the insertion order.
Example of LinkedHashMap class:
import [Link];
import [Link];
import [Link];
import [Link];
public class LinkedHashMapDemo {
public static void main(String args[]) {
// HashMap Declaration
LinkedHashMap<Integer, String> lhmap =
new LinkedHashMap<Integer, String>();
//Adding elements to LinkedHashMap
[Link](22, "Abey");
[Link](33, "Dawn");
[Link](1, "Sherry");
[Link](2, "Karon");
[Link](100, "Jim");
// Generating a Set of entries
Set set = [Link]();
// Displaying elements of LinkedHashMap
Iterator iterator = [Link]();
while([Link]()) {
[Link] me = ([Link])[Link]();
[Link]("Key is: "+ [Link]() +
"& Value is: "+[Link]()+"\n");
}
}
}
Output:
Key
Key
Key
Key
Key
is:
is:
is:
is:
is:
4.C)
22& Value is: Abey
33& Value is: Dawn
1& Value is: Sherry
2& Value is: Karon
100& Value is: Jim
Java TreeMap class
A TreeMap contains values based on the key. It implements the NavigableMap interface
and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order.
TreeMap is Red-Black tree based NavigableMap implementation. It is sorted according to
the
natural
ordering
of
its
keys.
TreeMap class implements Map interface similar to HashMap class. The main difference
between them is that HashMap is an unordered collection while TreeMap is sorted in the
ascending order of its keys. TreeMap is unsynchronized collection class which means it is
not suitable for thread-safe operations until unless synchronized explicitly.
Example of TreeMap class:
import
import
import
import
[Link];
[Link];
[Link];
[Link];
public class Details {
public static void main(String args[]) {
/* This is how to declare TreeMap */
TreeMap<Integer, String> tmap =
new TreeMap<Integer, String>();
/*Adding elements to TreeMap*/
[Link](1, "Data1");
[Link](23, "Data2");
[Link](70, "Data3");
[Link](4, "Data4");
[Link](2, "Data5");
/* Display content using Iterator*/
Set set = [Link]();
Iterator iterator = [Link]();
while([Link]()) {
[Link] mentry = ([Link])[Link]();
[Link]("key is: "+ [Link]() + " & Value is: ");
[Link]([Link]());
}
}
}
Output:
key
key
key
key
key
is:
is:
is:
is:
is:
1 & Value is: Data1
2 & Value is: Data5
4 & Value is: Data4
23 & Value is: Data2
70 & Value is: Data3
As you can see that we have inserted the data in random order however when we
displayed the TreeMap content we got the sorted result in the ascending order of keys.
4.D)
Java Hashtable class
A Hashtable is an array of [Link] list is known as a [Link] position of bucket is
identified by calling the hashcode() method.A Hashtable contains values based on the key.
It implements the Map interface and extends Dictionary class.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
Example of Hashtable:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
import [Link].*;
class TestCollection16{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
[Link](100,"Amit");
[Link](102,"Ravi");
[Link](101,"Vijay");
[Link](103,"Rahul");
for([Link] m:[Link]()){
[Link]([Link]()+" "+[Link]());
}
}
}
Output:103 Rahul
102 Ravi
101 Vijay
100 Amit
Difference between HashMap and Hashtable
HashMap and Hashtable both are used to store data in key and value form. Both are using hashing
technique to store unique keys.
But there are many differences between HashMap and Hashtable classes that are given below.
HashMap
Hashtable
1) HashMap is non synchronized. It is not-
Hashtable is synchronized. It is thread-safe and can
thread safe and can't be shared between many
be shared with many threads.
threads without proper synchronization code.
2) HashMap allows one null key and multiple
Hashtable doesn't allow any null key or value.
null values.
3) HashMap is a new class introduced in JDK
Hashtable is a legacy class.
1.2.
4) HashMap is fast.
Hashtable is slow.
5) We can make the HashMap as synchronized
Hashtable is internally synchronized and can't be
by
unsynchronized.
calling
Map
this
m
code
=
[Link](hashMap);
6) HashMap is traversed by Iterator.
Hashtable
is traversed
by
Enumerator
Iterator.
7) Iterator in HashMap is fail-fast.
Enumerator in Hashtable is not fail-fast.
8) HashMap inherits AbstractMap class.
Hashtable inherits Dictionary class.
Iterator/ListIterator
Both Iterator and ListIterator are used to iterate through elements of a collection
class. Using Iterator we can traverse in one direction (forward) while using
ListIterator we can traverse the collection class on both the directions(backward
and forward).
and
Iterator vs ListIterator
1) Iterator is used for traversing List and Set both.
We can use ListIterator to traverse List only, we cannot traverse Setusing ListIterator.
2) We can traverse in only forward direction using Iterator.
Using ListIterator, we can traverse a List in both the directions (forward and Backward).
3) We cannot obtain indexes while using Iterator
We can obtain indexes at any point of time while traversing a list using ListIterator. The
methods nextIndex() and previousIndex() are used for this purpose.
4) We cannot add element to collection while traversing it using Iterator, it throws
ConcurrentModificationException when you try to do it.
We can add element at any point of time while traversing a list using ListIterator.
5) We cannot replace the existing element value when using Iterator.
By using set(E e) method of ListIterator we can replace the last element returned by
next() or previous() methods.
6) Methods of Iterator:
hasNext()
next()
remove()
Methods of ListIterator:
add(E e)
hasNext()
hasPrevious()
next()
nextIndex()
previous()
previousIndex()
remove()
set(E e)
Iterator without Generics Example
Generics got introduced in Java 5. Before that there were no concept of Generics.
import [Link];
import [Link];
public class IteratorDemo1 {
public static void main(String args[]){
ArrayList names = new ArrayList();
[Link]("Chaitanya");
[Link]("Steve");
[Link]("Jack");
Iterator it = [Link]();
while([Link]()) {
String obj = (String)[Link]();
[Link](obj);
}
}
}
Output:
Chaitanya
Steve
Jack
In the above example we have iterated ArrayList without using Generics. Program ran fine
without any issues, however there may be a possibility of ClassCastException if you dont
use Generics (we will see this in next section).
Iterator with Generics Example
In the above section we discussed about ClassCastException. Lets see what is it and why it
occurs when we dont use Generics.
import [Link];
import [Link];
public class IteratorDemo2 {
public static void main(String args[]){
ArrayList names = new ArrayList();
[Link]("Chaitanya");
[Link]("Steve");
[Link]("Jack");
//Adding Integer value to String ArrayList
[Link](new Integer(10));
Iterator it = [Link]();
while([Link]()) {
String obj = (String)[Link]();
[Link](obj);
}
}
}
Output:
ChaitanyaException in thread "main"
Steve
Jack
[Link]: [Link] cannot be cast to [Link]
at [Link]([Link])
In the above program we tried to add Integer value to the ArrayList of String but we didnt
get any compile time error because we didnt use Generics. However since we type casted
the integer value to String in the while loop, we got ClassCastException.
Use Generics:
Here we are using Generics so we didnt type caste the output. If you try to add a integer
value to ArrayList in the below program, you would get compile time error. This way we
can avoid ClassCastException.
import [Link];
import [Link];
public class IteratorDemo3 {
public static void main(String args[]){
ArrayList<String> names = new ArrayList<String>();
[Link]("Chaitanya");
[Link]("Steve");
[Link]("Jack");
Iterator<String> it = [Link]();
while([Link]()) {
String obj = [Link]();
[Link](obj);
}
}
}
Note: We did not type cast iterator returned value[[Link]()] as it is not required when
using Generics.
ConcurrentModificationException while using
Iterator
import [Link];
public class ExceptionDemo {
public static void main(String args[]){
ArrayList<String> books = new ArrayList<String>();
[Link]("C");
[Link]("Java");
[Link]("Cobol");
for(String obj : books) {
[Link](obj);
//We are adding element while iterating list
[Link]("C++");
}
}
}
Output:
C
Exception in thread "main" [Link]
at [Link]$[Link](Unknown Source)
at [Link]$[Link](Unknown Source)
at [Link]([Link])
We cannot add or remove elements to the collection while using iterator over it.
Explanation From Javadoc:
This exception may be thrown by methods that have detected concurrent modification of
an object when such modification is not permissible.
For example, it is not generally permissible for one thread to modify a Collection while
another thread is iterating over it. In general, the results of the iteration are undefined
under these circumstances. Some Iterator implementations (including those of all the
general purpose collection implementations provided by the JRE) may choose to throw this
exception if this behavior is detected. Iterators that do this are known as fail-fast
iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic
behavior at an undetermined time in the future.
ListIterator Example
In this example we are traversing an ArrayList in both the directions.
import [Link];
import [Link];
import [Link];
public class ListIteratorExample {
public static void main(String a[]){
ListIterator<String> litr = null;
List<String> names = new ArrayList<String>();
[Link]("Shyam");
[Link]("Rajat");
[Link]("Paul");
[Link]("Tom");
[Link]("Kate");
//Obtaining list iterator
litr=[Link]();
[Link]("Traversing the list in forward direction:");
while([Link]()){
[Link]([Link]());
}
[Link]("\nTraversing the list in backward direction:");
while([Link]()){
[Link]([Link]());
}
}
}
Output:
Traversing the list in forward direction:
Shyam
Rajat
Paul
Tom
Kate
Traversing the list in backward direction:
Kate
Tom
Paul
Rajat
Shyam
Methods of ListIterator
1) void add(E e): Inserts the specified element into the list (optional operation).
2) boolean hasNext(): Returns true if this list iterator has more elements when traversing
the list in the forward direction.
3) boolean hasPrevious(): Returns true if this list iterator has more elements when
traversing the list in the reverse direction.
4) E next(): Returns the next element in the list and advances the cursor position.
5) int nextIndex(): Returns the index of the element that would be returned by a
subsequent call to next().
6) E previous(): Returns the previous element in the list and moves the cursor position
backwards.
7) int previousIndex(): Returns the index of the element that would be returned by a
subsequent call to previous().
8) void remove(): Removes from the list the last element that was returned by next() or
previous() (optional operation).
9) void set(E e): Replaces the last element returned by next() or previous() with the
specified element (optional operation).