Collection Framework
Collection Framework
Collections
--------------------
Array
---------
An array is an indexed collection of fixed number of homogenious(same type) data
elements.
The main advantage of arrays is we can represent multiple values by using single
variable so that redability of the code will be improved.
----------------------
limitations of arrays
----------------------
arrays are fixed in size i.e. once we creates an array there is no chance of
increasing or decreasing the size based on our requirement due to this to use
arrays concept compulsory we should know the size in advance which may not possible
always.
Arrays concept is not implemented based on some standard data structure and hence
readymate method support is not available for every requirement we have to write
the code explicitly which increases complexity of programming.
1. Collections are growable in nature i.e. based on our requirement we can increase
or decrease the size of collection
2. Collections can hold both homogenious(same type) and hetrogenious(different
types) elements.
3. *Every collection class is implemented based on some standard data-structure
hence for every requirement readymate method support is available.
4. Beaing a programmer we are responsible to use those methods and we are not
responsible to implement those methods.
-----------------------------------------------------
Differences between arrays and collections
-----------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------
Arrays Collections
-----------------------------------------------------------------------------------
-----------------------
1. Are Fixed in size |1. collections are Growable in nature
i.e. once we creates an array we can't |i.e. based on our requirement we can
increase or
increase or decrease the size based on |decrease the size.
our requirement. |
2. With repect to memory arrays are |2. With respect to memory collections are
not recommanded to use |Recommanded to use
3. with respect to performance arrays |3. With respect to performance collections
are
are recommanded to use |not recommanded to use.
4. Arrays can hold only homogenious |4. Collections can hold both homogenious
and
data type elements |hetrogenious elements.
5. There is no underlying data |5. Every collection class is
implemented based on
structure for arrays and hence ready- |some standard data structure and hence for
every
mate method support is not available. |requirement ready-mate method support is
for every requirement we have to write |available. Beaing a programmer we can use
these
the code explicitly which increases |methods directly and we are not responsible
to
complexity of programming. |implement those methods.
6. Arrays can hold both premitives |6. Collections can hold only object types
but not
and objects. |premitives.
-----------------------------------------------------------------------------------
-----------------------
-----------------
Collection
-----------------
If we want to represent a group of endividual objects as a single entity then we
should go for collection.
-------------------------
Collection Framework
-------------------------
It contains several classes and interfaces which can be used to represent a group
of individual objects as single entity.
java | c++
-------------------------------------
Collection | Container
------------------------------------------------------------
9 Key interfaces present inside collection framework
------------------------------------------------------------
1. Collection
2. List
3. Set
4. SortedSet
5. NavigableSet
6. Queue
7. Map
8. SortedMap
9. NavigableMap
------------------------------------------------------------
1. Collection(I):
------------------------------------------------------------
1. if we want to represent a group of individual objects as a single entity then we
should go for collection.
2. Collection interface defines the most common methods which are applicable for
any collection object.
2. List(I)
----------------------
It is the child interface of collection.
If we want to represent a group of individual objects as a single entity where
duplicates are allowed and the insertion order must be preserved then we should go
for list .
Collection(1.2v)
|
|
|
|
List(1.2V)
------------------------------------------------------
| | |
| | |
| | |
| | |
ArrayList(1.2V) LinkedList(1.2V) Vector (1.0V)
|
|
| Legacy classes
|
stack
Note : in 1.2 version vector and stack classes are re-engineered (modified) to
implement list interface.
3. Set(I)
------------------------------------------
1. It is child interface of collection
2. if we want to represent a group of individual objects as a single entity where
duplicates are not allowed and insertion order is not required then we should go
for set.
Collection(1.2v)
|
|
|
|
Set(I)(1.2V)-----------------|
| |
| |
| SortedSet(I)
|
HashSet(1.2V)
|
|
|
|
LinkedHashSet(1.4V)
4. SortedSet(I)
--------------------------------------
It is child interface of Set if we want to represent a group of individual objects
as a single entity where duplicates are not allowed and all objects should be
inserted according to some sorting order then we should go for sorted set.
Collection(1.2v)
|
|
|
|
Set(I)(1.2V)
|
|
|
|
SortedSet(1.2V)
5. NavigableSet(I)
--------------------------------------
it is child interface of SortedSet, it contains several methods for navigation
purposes.
Collection(I)(1.2v)
|
|
|
|
Set(I)(1.2V)
|
|
|
|
SortedSet(I)(1.2V)
|
|
|
|
NavigableSet(I)(1.6V)
|
|
|
TreeSet(1.2V)
-------------------------------------------------
Differences between List and Set
-------------------------------------------------
-----------------------------------------------------------------------------------
-----
List | Set
-----------------------------------------------------------------------------------
-----
1. Duplicates are allowed |1. Duplicates are not allowed
2. Insertion order preserved |2. Insertion order not preserved
-----------------------------------------------------------------------------------
-----
6. Queue(I)
-----------------
It is the child interface of collection, if we want to represent a group of
individual objects prior to processing then we should go for queue.
-----------
Usually Queue follows first in first out order but based on our requirement we can
implement our own priority order also.
e.g before sending a mail all mail-ids we have to store in some data structure in
which order we added mail ids in the same order only mail should be delivered for
these requirement queue is best choice.
Collection(I)(1.2v)
|
|
|
|
Queue(I)(1.5V)
------------------------------------------------------
| | |
| | |
| | |
| | |
PriorityQueue(1.5V) BlockingQueue(1.5V) ...
|
|
| PriorityBlockingQueue
|
|
| LinkedBlockingQueue
Note : All the above interfaces(Collection, List, Set, SortedSet, NavigableSet and
Queue) meant for representing a group of individual objects if we want to represent
a group of objects as key value pairs then we should go for map.
7. Map(I)
-------------------
Map is not child interface of collection
----
if we want to represent a group of objects as key value pairs then we should go for
map.
key value
--------------
s.No Name
--------------
101 Durga
102 Ravi
103 Shiva
Map(I)(1.2v)
Dictionary(AbstractClass) (1.0V)
| |
| |
| |
| |
-----------------------------------------------------------------------
-----|
| | | |
| | | |
Legacy classes
| | | |
| | | |
HashMap(1.2V) WeakHashMap(1.2V) IdentityHashMap(1.4V) HashTable
(1.0V)
| | |
| | |
| | |
| | Properties
(1.0V)
LinkedHashMap(1.4V)
8. SortedMap(I)
---------------------
It is a child interface of map.
If we want to represent a group of key-value pairs according to some sorting order
of keys then we should go for SortedMap.
in sorted map the sorting should be based on key but not based on value.
9. NavigableMap(I)
-----------------------
It is a child interface of sorted map.
it defines several methods for navigation purposes.
Map------------>SortedMap(I)(1.2V)--------------NavigableMap(I)
(1.6V)------->TreeMap(1.2V)
Collection(I)(1.2)
|
|-----------------------------------------------------------------
| | |
| | |
List(I)(1.2) Set(I) Queue(I)(1.5)
----------------- -------------- --------------------
| | | | | | |
| | | HS(1.2) | | |
| | | | | | |
AL LL Vector | SortedSet(I) PQ BQ(1.5)
(1.2) (1.2) |(1.0) LHS |(1.2) (1.5) -----
| (1.4) | | |
Stack NevigableSet(I) PBQ LBQ
(1.0) |(1.6) (1.5) (1.5)
(LegacyClasses) |
TreeSet
(1.2)
MAP(I)(1.2)
| Dictionary(AC)
| |
----------------------------------------|
| | | |
| | | |
| | | |
| | | |
HM WHM SortedMap(I) HashTable
|(1.2) (1.2) |(1.2) |(1.0)
| | |
LHM NavigableMap(I) Properties
(1.4) |(1.6) (1.0)(LegacyClasses)
|
TreeMap
(1.2)
Sorting
1. Comparable(I)
2. Comparator(I)
Cursors
1. Enumeration
2. Iterator(I)
3. ListIterator(I)
Utility Clases
1. Collections
2. Arrays.
-------------------
Collection(I)
-------------------
void clear()
boolean contains(Object o)
boolean containsAll(Collection c)
boolean isEmpty()
int size();
Object[] toArray();
Iterator iterator()
we can preserve insertion order with index and we can differentiate duplicate
objects by using index hence index will play very import role in list.
int indexOf(Object o)
returns index of first occurrence of 'o'
int lastIndexOf(Object o)
ListIterator listIterator();
Collection(I)(1.2v)
|
|
|
|
List(I)(1.2V)
------------------------------------------------------
| | |
| | |
| | |
| | |
ArrayList(1.2V) LinkedList(1.2V) Vector (1.0V)
|
|
| Legacy classes
|
stack
-----------------
ArrayList
-----------------
1. The underlying data structure is resizable array or growable array
2. Duplicates are allowed
3. Insertion order is preserved
4. Hetrogenious objects are allowed (except treeset and treemap every where
hetrogenious objects are allowed)
5. Null insertion is possible.
list.add("A");
list.add(10);
list.add("A");
list.add(null);
System.out.println(list);
list.remove(2);
System.out.println(list);
list.add(2, "M");
list.add("N");
System.out.println(list);
}
}
Usually use can use collections to hold and transfer objects from one place to
another place (container) to provide support for this requirement every collection
class by default implements serilizable and clonable interfaces.
ArrayList and Vector classes implements RandomAccess interface so that any random
element we can access with the same speed.
---------------
RandomAccess
---------------
e.g
ArrayList al = new ArrayList();
LinkedList ll = new LinkedList();
------------------------------------------
Differences between ArrayList and Vector
------------------------------------------
-----------------------------------------------------------------------------------
-
ArrayList | Vector
-----------------------------------------------------------------------------------
-
1. Every method present in the ArrayList|1. Every method present in the vectore is
is non-synchronized. |syncronized.
2. At a time multiple threads are |2. At a time only one thread is allowed to
allowedto operate on array list object | operate on vector object and hence it is
and hence it is not thread safe. |thread safe.
3. Relatively performance is high |3. Relatively performance is low because
because threads are not required to wait|Threads are required to wait to operate on
to operate on arraylist object. |vector object
4. introduced in 1.2 version and it is |4. Introduced in 1.0 version and it is
non-legacy. |legacy.
-----------------------------------------------------------------------------------
-
---------------------------------------------------
How to get Syncronized version of ArrayList Object
---------------------------------------------------
e.g.
ArrayList l = new ArrayList()
List l1 = Collections.SynchronizedList(l);
| |
| |
\/ \/
Synchronized Non-Synchronized
Similarly we can get synchronized version of Set and Map objects by using the
following methods of collections class.
-------------
LinkedList
-------------
1. The underlying data structure is doubledLinkedList
2. Insertion order is preserved.
3. Duplicate objects are allowed.
4. Hetrogenious objects are allowed.
5. Null insertion is possible.
6. LinkedList implements serilizable and clonable interfaces but not randomAccess
interface
7. LinkedList is best chioice if our frequent operation is insertion or deletion in
middle.
8. LinkedList is worst choice if our frequent operaiton is retrival operation.
Constructors
-------------
1. LinkedList l = new LinkedList();
Creates an empty LinkedList object
1. void addFirst(Object a)
2. void addLast(Object a)
3. Object getFirst()
4. Object getLast()
5. Object removeFirst()
6. Object removeLast()
----------------------------------------------
Difference between ArrayLink and LinkedList
----------------------------------------------
-----------------------------------------------------------------------------------
---------
ArrayList | LinkedList
-----------------------------------------------------------------------------------
---------
1.ArrayList is best choice if our |1. LinkedList is best choice if our fequent
frequent operation is retrival operation|operation is insertion or deletion in
middle.
2. ArrayList is worst choice if our |2. LinkedList is worst choice if our
frequent
frequent operation is insertion or |operation is retrival operation.
deletion in middle because internally |
several shift operations are performed |
3. Elements will be stored consequative |3. Elements won't be stored in
consequative
memory location and hence retrival |memory locations and hence retrival operation
operation will become easy |will become complex.
-----------------------------------------------------------------------------------
---------
Vector
--------------
Constructors
----------------
1. Vector v = new Vector();
Creates an empty vector object with defalut initial capacity 10 once vector reaches
its max capacity then a new vector object will be created with new capacity =
current capacity * 2.
--------------------------
Vector Specific Methods
--------------------------
1. To add objects
add(Object o)-----C
add(int index, Object o)-----L
addElement(Object o)-----V
2. To remove Objects
remove(Object o);----------C
removeElement(Object o);---V
remove(int index);---------L
removeElementAt(int index);-----------V
clear()-------C
removeAllElements();---------V
3. to get objcts
Object get(int index)--------L
Object elementAt(int index)--------V
Object firstElement(int index)--------V
Object lastElement(int index)--------V
4. Other methods
int size();
int capacity
Enumeration elements()
Stack
----------
It is the child class of vector.
It is a specially designed class for LastInFistOout(LIFO) order.
Constructor
----------------------
Stack s = new Stack()
Methods
--------------
1. Object push(object o)
to insert an object into the stack
2. Object pop()
to remove and return top of the stack
3. Object peek()
to return top of the stack without removal
4. boolean empty()
returns true if the stack is empty
5. int search(Object o)
returns offset if the element is available otherwise returns -1
index | |offset
2 | C |1
1 | B |2
0 | A |3
---------
----------------------------
The 3 cursors of java:
----------------------------
If we want to get objects one by one from the collection then we should go for
cursor.
there are 3 types of cursors available in java.
1. Enumeration
2. Iterator
3. ListIterator
1. Enumeration
-----------------
we can use Enumeration to get objects one by one from legacy collection objects.
we can create enumeration object by using elements method of vector class.
public enumerationElements();
e.g
Vector v = new Vector();
Enumeration e = v.elements();
Methods
-------------
1. public boolean hasMoreElements();
2. public Object nextElement();
Limitations of Enumeration
----------------------------
1. we can apply enumeration concept only for legacy classes and it is not a
universal cursor.
2. By using enumeration we can get only read access and we can't perform remove
operation.
3. To overcome above limitations we should go for iterator.
------------
Iterator(I)
------------
1. We can apply iterator concept for any collection object and hence it is
universal cursor.
2. By using iterator we can perform both read and remove operations.
3. We can create Iterator object by using iterator() method of collection
interface.
|---------------------------------------|
| public Iterator iterator(); |
|---------------------------------------|
Methods
------------
1. public boolean hasNext()
2. public Object next()
3. public void remove()
Limitations of Iterator
-------------------------
1. by using enumeration and iterator we can always move only towards forwards
direction and we can't move towards backword direction these are single direction
cursors but not by-directional cursors.
2. By using iterator we can perform only read and remove operations and we can't
perform replacement and addition of new objects.
3. To overcome above limitations we should go for ListIterator.
------------------
ListIterator(I)
------------------
1. by using ListIterator we can move either to the forward direction or backword
direction and hence it is by-directional cursors.
Methods
--------------
ListIterator is child interface of iterator and hence all methods present in
iterator by default available to the ListIterator.
Iterator(I)---->ListIterator(I)
if (s.equals("venki")){
ltr.remove();//[balakrishna, chiru, nag]
} else if (s.equals("nag")){
ltr.add("chaintu");//[balakrishna, chiru, nag, chitu]
} else if (s.equals("chiru")){
ltr.set("charan");//[balakrishna, charan, nag, chitu]
}
}
System.out.println(l);//[balakrishna, charan, nag, chitu]
}
}
--------------------------------------
Comparision table of three cursors
--------------------------------------
-----------------------------------------------------------------------------------
---------------------------------------------
Property | Enumeration | Iterator | ListIterator
-----------------------------------------------------------------------------------
---------------------------------------------
1. Where we can apply |only for legacy classes|for any collection obj |
applicable only for List objects
-----------------------------------------------------------------------------------
---------------------------------------------
2. is it legacy | Yes | No | No
-----------------------------------------------------------------------------------
---------------------------------------------
3. Movement |single Direction(only |single Direction(only | Bidirectional
|forward) |forward) |
-----------------------------------------------------------------------------------
---------------------------------------------
4. Allowed operations |only Read |Read and remove | Read, remove, replace
and addition
-----------------------------------------------------------------------------------
---------------------------------------------
5. How we can get? |by using elements |by using iterator() of | by using
listIterator() of list
|method of vector class |collection interface |interface
-----------------------------------------------------------------------------------
---------------------------------------------
6. Methods |2 Methods |3 Methods |9 Methods
|hasMoreElement() |hasNext() |
|nextElement() |next() |
| |remove() |
-----------------------------------------------------------------------------------
---------------------------------------------
InterImplementation of Cursors
------------------------------------
output
--------
java.util.Vector$1
java.util.Vector$Itr
java.util.Vector$ListItr
---------------------------------------------
Set(I)
---------------------------------------------
Collection(I)(1.2v)
|
|
|
|
Set(I)(1.2V)-----------------|
| |
| |
| SortedSet(I)
| |(1.2v)
HashSet(1.2V) |
| |
| NevigableSet(I)
| |(1.6v)
| |
LinkedHashSet(1.4V) TreeSet(1.2v)
---------------
HashSet
---------------
1. The underlying data structure is HashTable.
2. Duplicate values are not allowed.
3. Insertion order is not preserved and it is based on hashCode of objects.
4. Null insertion is allowed(only once as duplicate not allowed).
5. Hetrogenious objects are allowed.
6. Implements serilizable, clonable interface but not RandomAccess interface.
7. HashSet is best choice if our frequent operation is Search operation.
E.g
---------------------
Constructor
---------------------
---------------------------
FillRatio or LoadFactor
---------------------------
After filling how much ratio a new hashSet object will be created, this ratio is
called fill ratio or load factor for example fill ratio 0.75 means after filling
75% ratio a new HashSet object will be created automatically.
-----------------
LinkedHashSet
-----------------
It is child class of HashSet
It is exactly same as HashSet(including constructors and methods) except the
following differences
-----------------------------------------------------------------------------------
--
HashSet | LinkedHashSet
-----------------------------------------------------------------------------------
--
1. Underlying data structure is |1. Underlying data structure is
combination HashTable |LinkedList and HashTable.
2. Insertion order not preserved |2. Insertion order preserved.
3. Introduced in 1.2 version |3. Introduced in 1.4 version.
|
-----------------------------------------------------------------------------------
--
----------------------
SortedSet
----------------------
Collection(I)--------->Set(I)------------>SortedSet(I)
Note : The defalut natural sorting order for numbers is Accending order and for
String objects Alphabetic order.
Set[100,101,104,106,110,115, 120]
1. first()=>100
2. last()=> 120
3. headSet(106)=>[100,101,104]
4. tailSet(106)=>[106,110,115,120]
5. subSet(101, 115)=>[101,104,106,110]
6. comparator() =>null
-------------
TreeSet
-------------
1. The underlying data structure is balanced tree.
2. duplicate objects are not allowed.
3. insertion order not preserved
4. Hetrogenious objects are not allowed otherwise we will get RuntimeException
saying ClassCastException.
5. null insertion is allowed but only once.
6. TreeSet implements Serilizable and Clonable but not RandomAccess interface.
All Objects will be inserted based on some sorting order, it may be default natural
sorting order or customized sorting order.
-------------------
Constructors
-------------------
1. TreeSet t = new TreeSet();
creates an empty treeSet object where the elements will be inserted according to
default natural sorting order.
2. TreeSet t = new TreeSet(Comprator c);
Creates an empty treeSet object where the elements will be inserted according to
customized sorting order specified by comprator object.
-------------------
null acceptance
-------------------
1. For non empty tree set if we are trying to insert null then we will get
NullPointerException.
2. For empty tree set as a first element null is allowed but after inserting that
null if we are trying to insert any other then we will get runtime exception saying
NullPointerException.
Note : * Until 1.6 version null is allowed as the first element to the empty
TreeSet but from java 1.7 version onwards null is not allowed even as first element
i.e. 'null' such type of story not applicable for TreeSet from java 1.7 version
onwards.
RuntimeException: ClassCastException.
if we are depending on default natural sorting order compulsory the object should
be Homogenious and comparable otherwise we will get RuntimeException saying
ClassCastException.
------------------
Comparable(I)
------------------
obj1.compareTo(obj2)
|
|-----returns -ve if object 1 has to come before obj2
|
|-----returns +ve if object 1 has to come after obj2
|
|-----returns 0 if object 1 and object 2 are equal.
|
if we are depending on default natural sorting order then while adding objects into
the tree set JVM will call compareTo() method.
TreeSet t = new TreeSet();
t.add("k");
t.add("Z");
t.add("A");
t.add("A");
sopln(t); //[A,K,Z]
K
/ \
/ \
/ \
/ \
A Z
Note : if default natural sorting order not available or if we are not satisfied
with default natural sorting order then we should go for customized sorting by
using comparator interface.
-----------------
Comprator
-----------------
Comprator present in java.util package and it defines two methods compare() &
equals().
Write a program to insert integer objects into the TreeSet where the sorting order
is decending order.
class TreeSetDemo3{
public static void main(String[] args){
TreeSet t = new TreeSet(new MyComparator());
t.add(10);
t.add(0);
t.add(15);
t.add(5);
t.add(20);
t.add(20);
System.out.println(t);
}
}
t.add(10);
t.add(0); compare(0, 10)
root
10
/ \
/ \
/ \
/ \
left 15 0 right
/ /
/ /
/ /
/ /
20 5
At line 1 if we are not passing comparator object then internally jvm will call
compareTo() method which is ment for default natural sorting order in this case the
output is 0,5,10,15,20.
At line 1 if we are passing comparator object then JVM will call compare() method
which is ment for customized sorting in this case output is [20,15,10,5,0].
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-
checkout core java collection part-10
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-
Write a program to insert String object into the tree set where all elements should
be inserted according to reverse of alpha betical order.
Write a program to insert StringBuffer objects into the TreeSet where sorting order
is alphabetical order.
Note : if we are depending on default natural sorting order compulsory the object
should be homogenious and comparable otherwise we will get RuntimeException saying
classCastException.
if we are defining our own sorting by comprator then objects need not be comparable
and homogenious i.e. we can add hetrogenious non comparable objects also.
Write a program to insert STring and StringBuffer object into treeSet where sorting
order is increasing length order, if two objects having same length then consider
there alphabetical order.
String name;
int eid;
@Override
public String toString() {
return name + "--" + eid;
}
@Override
public int compareTo(Object o) {
int eid1 = this.eid;
Employee e = (Employee) o;
int eid2 = e.eid;
if (eid1 < eid2) {
return -1;
} else if (eid1 > eid2) {
return 1;
} else
return 0;
}
}
class CompComp {
public static void main(String[] args) {
Employee e1 = new Employee("nag", 100);
Employee e2 = new Employee("balaiah", 200);
Employee e3 = new Employee("chiru", 50);
Employee e4 = new Employee("venki", 150);
Employee e5 = new Employee("nag", 100);
TreeSet t = new TreeSet();
t.add(e1);
t.add(e2);
t.add(e3);
t.add(e4);
t.add(e5);
System.out.println(t);
TreeSet t1 = new TreeSet(new MyComparator());
t1.add(e1);
t1.add(e2);
t1.add(e3);
t1.add(e4);
t1.add(e5);
System.out.println(t1);
}
}
output:
[chiru--50, nag--100, venki--150, balaiah--200]
[balaiah--200, chiru--50, nag--100, venki--150]
------------------------------------------------
Comparison table of set implemented classes.
------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------------------------------------
Property | HashSet |
LinkedHashSet | TreeSet
-----------------------------------------------------------------------------------
-------------------------------------------------------------
1. underlying data structure | HashTable | Combination of
LinkedList and HashTable | Balanced Tree |
2. Duplicate objects | Not Allowed | Not Allowed
| Not Allowed
3. Insertion order | Not preserved | Preserved
| Not Preserved
4. Sorting order | NA | NA
| Applicable
5. Hetrogenious objects | Allowed | Allowed
| Not Allowed
6. Null Acceptance | Allowed | Allowed
| For empty TreeSet as
| |
| first element null is
| |
| allowed till 1.6 Version only.
-----------------------------------------------------------------------------------
-------------------------------------------------------------
Note : For empty TreeSet as the first element null is allowed but this rule is
applicable until 1.6 version only and from 1.7 version onwards null is not allowed
even as the first element.
----------------
Map(I)
----------------
MAP(I)(1.2)
| Dictionary(AC)
| |
------------------------------------------------|
| | | | |
| | | | |
| | | | |
| | | | |
HM IHM WHM SortedMap(I) HashTable
|(1.2) (1.4) (1.2) |(1.2) |(1.0)
| | |
LHM NavigableMap(I) Properties
(1.4) |(1.6) (1.0)(LegacyClasses)
|
TreeMap
(1.2)
key | value
--------------------------
101 | Durga
102 | Ravi
103 | Shiva
104 | Pawan
2. void putAll(Map m)
3. Object get(Object key) // returns the value associated with specified key.
4. Object remove(Object key) //Removes the entry associated with Specified key.
5. boolean containsKey(Object key)
6. boolean containsValue(Object value)
7. boolean isEmpty()
8. int size()
9. void clear();
1. Set keySte()
2. Collection values()
3. Set entrySet()
Ablove three methods are ment for collection views of map.
------------
Entry(I)
------------
A map is a group of key-value pairs and each key-value pair is called an entry
hence map is considered as a collection of entry objects.
Without existing Map object there is no chance of existing entry object hence entry
enterface is defined inside map interface.
interface Map {
interface Entry{
Object getKey();
Object getValue();
Object setValue(Object obj);
}
}
above methods are entry specific methods and we can apply only on Entry object.
Constructors
---------------
1. HashMap m = new HashMap();
creates an empty HashMap object with defalut initial capacity 16 and defalut fill
ratio 0.75.
2. HashMap m = new HashMap(int initialCapacity);
Creates an empty HashMap object with specified initialCapacity and defalut fill
ratio i.e. 0.75.
3. HashMap m = new HashMap(int initialCapacity, int fillRatio);
4. HashMap m = new HashMap(Map m);
e.g.
import java.util.*;
Map m1 = Collections.synchronizedMap(m);
| |
|-----synchronized map |-------non-synchronized map
| |
------------------
LinkedHashMap
------------------
1. It is the child class of HashMap
2. It is exactly same as HashMap(including methods and constructors) except the
following differences.
-------------------------------------------------------------------------------
HashMap | LinkedMap
-------------------------------------------------------------------------------
1. The underlying data structure|1. Underlying dataStructure is Combination of
is HashTable. |LinkedList and HashTable(Hybrid DataStructure)
2. Insertion order is not |2. Insertion order is preserved
preserved and it is based on |
HashCode of keys |
3. Introduced in 1.2 version |3. Introduced in 1.4 version.
-------------------------------------------------------------------------------
In the above HashMap program if we replace HashMap with LinkedHashMap then output
is
{chiranjeevi=700, balaiah = 800, venkatesh=200, nargajuna=500}
i.e. insertion order is preserved.
Note : LinkedHashSet and LinkedHashMap are commonly user for developing cache based
applications.
e.g.
Integer i1 = Integer(10);
Integer i2 = Integer(10);
sopln(i1 == i2);//False
sopln(i1.equals(i2));//True
-----------------------
IdentityHashMap
-----------------------
it is exactly same as HashMap(including methods and constructors) except the
following difference.
In the case of Normal HashMap JVM will use .equals() method to identify duplicate
keys, which is ment for content comparision.
But in the case of IdentityHashMap JVM will use == operator to identify duplicate
keys which is ment for reference comparision(address comparision).
e.g.
HashMap m1 = new HashMap();
Integer i1 = Integer(10); i1 and i2 are duplicate keys because
i1.equals(i2)
Integer i2 = Integer(10); returns true.
m.put(i1, "pawan");
m.put(i2, "kalyan");
sonpln(m);
if we replace HashMap with IdentityHashMap then i1 and i2 are not duplicate keys
because i1 == i2 returns false.
----------------
WeakHashMap
----------------
it is exactly same as HashMap except the following difference.
in the case of HashMap even though object doesn't have any reference it is not
elegible for GC if it is associated with HashMap i.e. HashMap dominates Garbage
Collector.
But in the case of WeakHashMap, if object doesn't contain any references it is
elegible for GC even though object associated with WeakHashMap i.e. Garbage
collector dominates WeakHashMap.
}
}
class Temp{
public String toString() {
return "temp";
}
@Override
protected void finalize() throws Throwable {
System.out.println("Finalize method called");
}
}
in the above example temp object not elegible for GC because it is associated with
HashMap.
In this case output is {temp=durga}
{temp=durga}
In the above program if we replace HashMap with WeakHashMap then Temp object is
elegible for GC in this case output is
{temp = durga}
finalize method call
{}
--------------
SortedMap
--------------
It is child interface of map if we want represent a group of object as a group of
key value pairs acoording to some sorting order of key then we should go for sorted
map.
Sorting is based on the key but not based on value.
-------------------------------------------------------
SortedMap defines the following specific methods.
-------------------------------------------------------
Object firstKey();
Object lastKey();
SortedMap headMap(Object key)
SortedMap tailMap(Object key)
SortedMap subMap(Object key, Object key2)
Comparator comparator()
101--->A
103--->B
104--->C
107--->D
155--->E
136--->F
firstKey(); --->101
lastKey(); --->136
headMap(Object key) ---> {101=A, 103=B, 104=c}
tailMap(Object key) ---> {107=D, 125=E, 136=F}
subMap(Object key, Object key2) ---> {103=B, 104=C, 107=D}
comparator() ---> null
-----------
TreeMap
-----------
1. The underlying datastructure is red black tree
2. Insertion order is not preserved and it is based on some sorting order keys.
3. Duplicate keys are not allowed, but values can be duplicated.
4. If we are depending on defalut natural sorting order then keys should be
homogenious and comparable otherwise we will get RuntimeException saying
ClassCastException.
5. If we are defining our own sorting by comparator then keys need not be
homogenious and comparable. we can take hetrogenious non-comparable objects also.
6. Whether we are depending on defalut natural sorting order or customized sorting
order there are not restrictions for values, we can take hetrogenious non-
comparable objects also.
---------------------
Null Acceptance
---------------------
1. For non-empty TreeMap if we are trying to insert an entry with null key then we
will get RuntimeException saying null pointer exception.
2. For empty tree map as first entry with null key is allowed but after inserting
that entry if we are trying to insert any other entry then we will get
RuntimeException saying NullPointerException.
Note : The above null acceptance rule applicable until 1.6 version only, from 1.7
version onwards null is not allowed for key.
But for values we can use null any number of times there is no restriction whether
it is 1.6 version or 1.7 version.
------------------------
Constructors
------------------------
import java.util.*
class TreeMapDemo3{
public static void main(String[] args){
TreeMap m = TreeMap();
m.put(100, "ZZZ");
m.put(103, "YYY");
m.put(101, "XXX");
m.put(104, 106);
m.put("FFFF", "XXX");//CCE
m.put(null, "XXX");//NPE
System.out.println(m);
//{100=ZZZ,101=XXX,103=YYY,104=106}
}
}
import java.util.*
class TreeMapDemo{
public static void main(String[] args){
TreeMap m = TreeMap();
m.put("XXX", 10);
m.put("AAA", 20);
m.put("ZZZ", 30);
m.put("LLL", 40);
System.out.println(m);
//{ZZZ=30,XXX=10,LLL=40, AAA=20}
}
}
----------------
HashTable
----------------
1. The underlying dataStructure for HashTable is "HashTable".
2. insertion order is not preserved and it is based on HashCode of keys.
----------------
3. Duplicate keys are not allowed but values can be duplicated.
4. Hetrogenious objects are allowed for both keys and values.
5. null is not allowed for both key and value otherwise we will get
RuntimeException saying NullPointerException.
6. It implements Serilizable and Colnable interfaces but not RandomAccess
interface.
7. Every method present in HashTable is synchronized and hence HashTable object is
thread safe.
8. HashTable is best choice if our frequent operation is retrival operation(search
operation).
---------------------
Constructors
---------------------
class Temp1 {
int i;
public Temp1(int i) {
this.i = i;
}
@Override
public int hashCode() {
return i;
}
@Override
public String toString() {
return i + " ";
}
}
output:
{6 =C, 16 =F, 5 =A, 15 =D, 2 =B, 23 =E}
---------
10| |
| |
---------
9| |
| |
---------
8| |
| |
---------
7| |
| |
---------
6|6=C | From top to bottom
| | from Right to left
---------
5|5=A,16=F|
| |
---------
4|15=D |
| |
---------
3| |
| |
---------
2|2=B |
| |
---------
1|23=E |
| |
---------
0| |
| |
---------
-------------
Properties
-------------
In our program if any thing which changes frequently (like userName, password,
mailId, mobileNo, etc) are not recommanded to hardcode it inside java program
because if there is any change to reflect that change recompilation, rebuild, and
re-deploy application are required even some times server restart also required
which creates a big business impact to the client.
We can overcome this problem by using properties file, such type of variable things
we have to configure in the properties file.
From that properties file we have to read into java program and we can use those
properties.
The main advantage of this approach is if there is a change in properties file to
reflect that change just re-deployment is enough which won't create any business
impact to the client.
We can use java properties object to hold properties which are coming from
properties file.
In normal map (like HashMap, HashTable, TreeMap key and value can be any type but
in the case of properties key and value should be only String type.
Constructor
--------------
Properties p = new Properties;
3. Enumeration propertyNames()
Returns all property names present in properties object.
Another ecample.
class PropertiesDemo2{
public static void main(String[] args) throws Exception{
Properties p = new Properties();
FileInputStream fis = new FileInputStream("db.properties");
p.load(fis);
String url = p.getProperty("url");
String user = p.getProperty("user");
String pwd = p.getProperty("pwd");
Connection con = DriverManager.getConnection(url, user, pwd);
}
}
-----------
Queue
-----------
Collection(I)(1.2)
|
|-----------------------------------------------------------------
| | |
| | |
List(I)(1.2) Set(I) Queue(I)(1.5)
----------------- -------------- --------------------
| | | | | | |
| | | HS(1.2) | | |
| | | | | | |
AL LL Vector | SortedSet(I) PQ BQ(1.5)
(1.2) (1.2) |(1.0) LHS |(1.2) (1.5) -----
| (1.4) | | |
Stack NevigableSet(I) PBQ LBQ
(1.0) |(1.6) (1.5) (1.5)
(LegacyClasses) |
TreeSet
(1.2)
Usually queue follows First in First out order but based on our requirement we can
implement our own priority order also(PriorityQueue)
From 1.5 version onwards LinkedList class also implements Queue interface.
-----------------------------------
Queue Interface specific methods.
-----------------------------------
boolean offer(Object o)
To add an object into the queue
Object peek()
to return head leement of the queue. If queue is empty then this method
returns null.
Object element()
to return head element of the queue. If queue is empty then this method
raises RE: NoSuchElementException
Object poll()
to remove and return head element ofthe queue. If queue is empty then this
method returns null.
Object remove()
to remove and return head element of the queue. if queue is empty then this
method raises an NoSuchElementException.
-----------------
PriorityQueue
-----------------
1. if we want to represent a group of individual objects prior to processing
according to some priority then we should go for PriorityQueue.
2. The Priority can be either default natural sorting order or customized sorting
order defined by comparator.
----------------------
Constructors
----------------------
1. PriorityQueue q = new PriorityQueue();
creates an empty priority queue with default initial capacity 11 and all objects
will be inserted according to default natural sorting order.
Some platforms won't provide proper support for thread priorities and priority
queue.
@Override
public int compare(Object obj1, Object obj2) {
String s1 = (String) obj1;
String s2 = obj2.toString();
return s2.compareTo(s1);
}
}
------------------------------------------------------
1.6 Version Enhancements in Collection Framework:
------------------------------------------------------
As part of 1.6 version the following 2 concepts introduced in collection framework
1. NavigableSet(I)
2. NavigableMap(I)
NavigableSet(I)
---------------------
it is child interface of SortedSet(I) and it defines several methods for navigation
purposes.
Collection(I)(1.2)------>Set(I)(1.2)------->SortedSet(I)(1.2)----------
>NavigableSet(I)(1.5)---------->TreeSet(1.2)
floor(e)
it returns highest element which is <= e
lower(e)
it returns highest element which is < e
ceiling(e)
it returns lowest element which is >= e
higher(e)
it returns highest element which is > e
pollFirst()
remove and return first element
pollLast()
remove and return last element
descendingSet()
it returns NavigableSet in reverse order
e.g
NavigableMap(I)
--------------------
NavigableMap is child interface of SortedMap interface.
It defines several methods for navigation purposes.
Map(I)------->SortedMap(I)------------------->NavigableMap(I)---------->TreeMap
floorKey(e)
lowerKey(e)
ceilingKey(e)
higherKey(e)
pollFirstEntry()
pollLastEntry()
descendingMap()
e.g
------------------------
Utility classes
------------------------
Collections
------------------------
Collections class defines several utility methods for collection objects like
sorting searching reversing etc.
Demo program for sorting elements of list according to default Natural sorting
order.
output :
Before Sorting:[Z, A, K, N]
After Sorting:[Z, N, K, A]
if the list is sorted according to default naturla sorting order then we have to
use this methods.
we have to use this method if list is sorted acoording to customized sorting order.
Conclusions.
---------------
1. The above search methods internally will use binary search algorithm
4. Before calling binary search method compulsory list should be sorted, otherwise
we will get unpredictable results.
|---------------------------------------|
| Z |A |M |K |a |
| | | | | |
|---------------------------------------|
-1 -2 -3 -4 -5-------Insertion point
|---------------------------------------|
|A |K |M |Z |a |
| | | | | |
|---------------------------------------|
0 1 2 3 4------->index
Collection.binarySearch(l,"Z");-->3
Collection.binarySearch(l,"J");-->2
}
}
|---------------------------------------|
| 15 |0 |20 |10 |5 |
| | | | | |
|---------------------------------------|
-1 -2 -3 -4 -5-------Insertion point
|---------------------------------------|
|20 |15 |10 |5 |0 |
| | | | | |
|---------------------------------------|
0 1 2 3 4------->index
Collection.binarySearch(l,10,new MyComparator());2
Collection.binarySearch(l,13,new MyComparator());+3
Collection.binarySearch(l,17,new MyComparator());unpredicatable
Collection.binarySearch(l,17,new MyComparator());-2
Note: for the list of n elements in the case of binary search method
e.g.
------------------------
| A | K |Z |
| | | |
------------------------
-----------------------------
Reversing elements of list
-----------------------------
Collections class defines the following reverse method to reverse elements of list.
-------------------------------------------------
| public static void reverse(List l) |
-------------------------------------------------
---------------------------
Reverse vs ReverseOrder
---------------------------
We can use reverse() method to reverse order of elements of list where as we can
use reverse order method to get reversed comparator.
---------------------------------------------------------
|Comparator c1 = Collections.reverseOrder(Comprator c) |
---------------------------------------------------------
Arrays
---------
Arrays class is an utility class to define several utility methods for Arrays
objects.
Arrays class defines the following sort methods to sort elements of primitive and
object type arrays.
@Override
public int compare(Object obj1, Object obj2) {
String s1 = obj1.toString();
String s2 = obj2.toString();
return s2.compareTo(s1);
}
}
we can sort premitive arrays only based on default natural sorting order where as
we can sort object arrays either based on default natural sorting order or based on
customized sorting order.
Note : all rules of arrays class binary search methods are exactly same as
collections class binary search methods.
}
}
class MyComparator implements Comparator {
public int compare(Object obj1, Object obj2) {
String s1 = obj1.toString();
String s2 = obj2.toString();
return s2.compareTo(s1);
}
}
1.
|---------------------------------------|
| 10 |5 |20 |11 |6 |
| | | | | |
|---------------------------------------|
-1 -2 -3 -4 -5 -5
|---------------------------------------|
a--> |5 |6 |10 |11 |20 |
| | | | | |
|---------------------------------------|
0 1 2 3 4
Arrays.binarySearch(a,6); 1
Arrays.binarySearch(a,14); -5
2. ------------------------
| A | Z |B |
| | | |
------------------------
-1 -2 -3 -4
------------------------
| A | K |Z |
| | | |
------------------------
0 1 2
Arrays.binarySearch(s,"z"); 2
Arrays.binarySearch(s,"S");-3
3. ------------------------
| A | Z |B |
| | | |
------------------------
-1 -2 -3 -4
------------------------
| A | K |Z |
| | | |
------------------------
0 1 2
binarySearch(s, "Z", new MyComparator());
0
binarySearch(l, "S", new MyComparator());
-2
binarySearch(r,"N");
unpredictable Result.
-------------------------------
Conversion of Array to List
-------------------------------
public static List asList(Object[] a)
Strictly speaking this method won't create an indipendent list object for the
existing array we are getting list view.
String[]--|
|--->
| A | Z | B |
|---->
|
List l---|
by using array reference if we perform any change automatically that change will be
reflected to the list similarly by using list reference if we perform any change
that change will be reflected automatically to the array.
2. by using list reference we can't perform any operation which varies the size
otherwise we will get runtime exception saying UnsupportedOperationException.
l.add("M");------->RE: UnsupportedOperationException
l.remove(1);--->RE: UnsupportedOperationException
l.set(1,"N");-->Valid
by using list reference we are not allowed to replace with hetrogenious objects
otherwise we will get runtime exception saying ArraStoreException