Vous êtes sur la page 1sur 31

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 framework.The java.util 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 java.util.Collection 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 java.util.Collections 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 elements.It 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 java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();//creating arraylist
al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Or (Iterating through for:each loop// Replacement of lines 11-14)


1.
2.

for(String obj:al)
System.out.println(obj);
O/P :
Ravi
Vijay
Ravi
Ajay

1.
2.
3.
4.
5.
6.

Example of addAll(Collection c) method


import java.util.*;
class TestCollection4{
public static void main(String args[]){

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


al.add("Ravi");

7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.

al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Sonoo");
al2.add("Hanumat");
al.addAll(al2);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
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 java.util.*;
class TestCollection5{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
al.removeAll(al2);
System.out.println("iterating the elements after removing the elements of al2...");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

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 java.util.*;
class TestCollection6{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
al.retainAll(al2);
System.out.println("iterating the elements after retaining the elements of al2...");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

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 java.util.*;
public class TestCollection7{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

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 java.util.*;
class TestVector1{
public static void main(String args[]){
Vector<String> v=new Vector<String>();//creating vector
v.add("umesh");//method of Collection
v.addElement("irfan");//method of Vector
v.addElement("kumar");
//traversing elements using Enumeration
Enumeration e=v.elements();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}

Output:

umesh
irfan
kumar

Eg2)
import java.util.*;
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*/
vec.addElement("Apple");
vec.addElement("Orange");
vec.addElement("Mango");
vec.addElement("Fig");
/* check size and capacityIncrement*/
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity increment is: "+vec.capacity());
vec.addElement("fruit1");
vec.addElement("fruit2");
vec.addElement("fruit3");
/*size and capacityIncrement after two insertions*/
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after increment is: "+vec.capacity());
/*Display Vector elements*/
Enumeration en = vec.elements();
System.out.println("\nElements are:");
while(en.hasMoreElements())
System.out.print(en.nextElement() + " ");
}
}

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 elements.It 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 = Collections.synchronizedSet(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 java.util.HashSet;
public class HashSetExample {
public static void main(String args[]) {
// HashSet declaration
HashSet<String> hset =
new HashSet<String>();
// Adding elements to the HashSet
hset.add("Apple");
hset.add("Mango");
hset.add("Grapes");
hset.add("Orange");
hset.add("Fig");
//Addition of duplicate elements
hset.add("Apple");
hset.add("Mango");
//Addition of null values
hset.add(null);
hset.add(null);
//Displaying HashSet elements
System.out.println(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 java.util.LinkedHashSet;
public class LinkedHashSetExample {
public static void main(String args[]) {
// LinkedHashSet of String Type
LinkedHashSet<String> lhset = new LinkedHashSet<String>();
// Adding elements to the LinkedHashSet
lhset.add("Z");
lhset.add("PQ");
lhset.add("N");
lhset.add("O");
lhset.add("KK");
lhset.add("FGH");
System.out.println(lhset);
// LinkedHashSet of Integer Type
LinkedHashSet<Integer> lhset2 = new LinkedHashSet<Integer>();
// Adding elements
lhset2.add(99);
lhset2.add(7);
lhset2.add(0);
lhset2.add(67);
lhset2.add(89);
lhset2.add(66);
System.out.println(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 java.util.*;
class TestCollection10{
public static void main(String args[]){
LinkedHashSet<String> al=new LinkedHashSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){

13.
14.
15.
16.

System.out.println(itr.next());
}
}
}
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 = Collections.synchronizedSortedSet(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 java.util.TreeSet;
public class TreeSetExample {
public static void main(String args[]) {
// TreeSet of String Type
TreeSet<String> tset = new TreeSet<String>();
// Adding elements to TreeSet<String>
tset.add("ABC");
tset.add("String");
tset.add("Test");
tset.add("Pen");
tset.add("Ink");
tset.add("Jack");
//Displaying TreeSet
System.out.println(tset);
// TreeSet of Integer Type
TreeSet<Integer> tset2 = new TreeSet<Integer>();

// Adding elements to TreeSet<Integer>


tset2.add(88);
tset2.add(7);
tset2.add(101);
tset2.add(0);
tset2.add(3);
tset2.add(222);
System.out.println(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 java.util.HashSet;
import java.util.TreeSet;
import java.util.Set;
class ConvertHashSettoTreeSet{
public static void main(String[] args) {
// Create a HashSet
HashSet<String> hset = new HashSet<String>();
//add elements to HashSet
hset.add("Element1");
hset.add("Element2");
hset.add("Element3");
hset.add("Element4");
// Displaying HashSet elements
System.out.println("HashSet contains: "+ hset);
// Creating a TreeSet of HashSet elements
Set<String> tset = new TreeSet<String>(hset);
// Displaying TreeSet elements
System.out.println("TreeSet contains: ");
for(String temp : tset){
System.out.println(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 Map.Entry 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 java.util.HashMap 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 beginnersbook.com;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;

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*/
hmap.put(12, "Chaitanya");
hmap.put(2, "Rahul");
hmap.put(7, "Singh");
hmap.put(49, "Ajeet");
hmap.put(3, "Anuj");
/* Display content using Iterator*/
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
System.out.println(mentry.getValue());
}
Or
1.
2.
3.

for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
/* Get values based on key*/
String var= hmap.get(2);
System.out.println("Value at index 2 is: "+var);
/* Remove values based on key*/
hmap.remove(3);
System.out.println("Map key and values after removal:");
Set set2 = hmap.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry mentry2 = (Map.Entry)iterator2.next();
System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
System.out.println(mentry2.getValue());
}
}
}

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 java.util.LinkedHashMap;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;
public class LinkedHashMapDemo {
public static void main(String args[]) {
// HashMap Declaration
LinkedHashMap<Integer, String> lhmap =
new LinkedHashMap<Integer, String>();
//Adding elements to LinkedHashMap
lhmap.put(22, "Abey");
lhmap.put(33, "Dawn");
lhmap.put(1, "Sherry");
lhmap.put(2, "Karon");
lhmap.put(100, "Jim");
// Generating a Set of entries
Set set = lhmap.entrySet();
// Displaying elements of LinkedHashMap
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print("Key is: "+ me.getKey() +
"& Value is: "+me.getValue()+"\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

java.util.TreeMap;
java.util.Set;
java.util.Iterator;
java.util.Map;

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*/
tmap.put(1, "Data1");
tmap.put(23, "Data2");
tmap.put(70, "Data3");
tmap.put(4, "Data4");
tmap.put(2, "Data5");
/* Display content using Iterator*/
Set set = tmap.entrySet();

Iterator iterator = set.iterator();


while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
System.out.println(mentry.getValue());
}
}
}

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 list.Each list is known as a bucket.The 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 java.util.*;
class TestCollection16{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

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
=

Collections.synchronizedMap(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 java.util.ArrayList;
import java.util.Iterator;
public class IteratorDemo1 {
public static void main(String args[]){
ArrayList names = new ArrayList();
names.add("Chaitanya");
names.add("Steve");
names.add("Jack");
Iterator it = names.iterator();
while(it.hasNext()) {
String obj = (String)it.next();
System.out.println(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 java.util.ArrayList;
import java.util.Iterator;
public class IteratorDemo2 {
public static void main(String args[]){
ArrayList names = new ArrayList();
names.add("Chaitanya");
names.add("Steve");
names.add("Jack");
//Adding Integer value to String ArrayList
names.add(new Integer(10));
Iterator it = names.iterator();
while(it.hasNext()) {
String obj = (String)it.next();
System.out.println(obj);
}
}
}

Output:
ChaitanyaException in thread "main"
Steve
Jack
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at beginnersbook.com.Details.main(Details.java:18)

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 java.util.ArrayList;
import java.util.Iterator;
public class IteratorDemo3 {
public static void main(String args[]){
ArrayList<String> names = new ArrayList<String>();
names.add("Chaitanya");
names.add("Steve");
names.add("Jack");
Iterator<String> it = names.iterator();
while(it.hasNext()) {
String obj = it.next();
System.out.println(obj);
}
}
}

Note: We did not type cast iterator returned value[it.next()] as it is not required when
using Generics.

ConcurrentModificationException while using


Iterator
import java.util.ArrayList;
public class ExceptionDemo {
public static void main(String args[]){
ArrayList<String> books = new ArrayList<String>();
books.add("C");
books.add("Java");
books.add("Cobol");
for(String obj : books) {
System.out.println(obj);
//We are adding element while iterating list
books.add("C++");
}
}
}

Output:
C
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at beginnersbook.com.Details.main(Details.java:12)

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 java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class ListIteratorExample {
public static void main(String a[]){
ListIterator<String> litr = null;
List<String> names = new ArrayList<String>();
names.add("Shyam");
names.add("Rajat");
names.add("Paul");
names.add("Tom");
names.add("Kate");
//Obtaining list iterator
litr=names.listIterator();
System.out.println("Traversing the list in forward direction:");
while(litr.hasNext()){
System.out.println(litr.next());
}
System.out.println("\nTraversing the list in backward direction:");
while(litr.hasPrevious()){
System.out.println(litr.previous());
}
}
}

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

Vous aimerez peut-être aussi