0% found this document useful (0 votes)
3 views

Collection Basic Questions and Answer

The document provides an overview of the Java Collections Framework, detailing the differences between arrays and collections, as well as the various interfaces and classes within the framework. It explains the advantages of collections, such as their growable nature and ability to hold heterogeneous data types, and outlines key interfaces like Collection, List, Set, Map, and their respective implementations. Additionally, it covers cursors for traversing collections, including Enumeration, Iterator, and ListIterator, along with their methods and limitations.

Uploaded by

Bl Gocher
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Collection Basic Questions and Answer

The document provides an overview of the Java Collections Framework, detailing the differences between arrays and collections, as well as the various interfaces and classes within the framework. It explains the advantages of collections, such as their growable nature and ability to hold heterogeneous data types, and outlines key interfaces like Collection, List, Set, Map, and their respective implementations. Additionally, it covers cursors for traversing collections, including Enumeration, Iterator, and ListIterator, along with their methods and limitations.

Uploaded by

Bl Gocher
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 42

*******************: COLLECTION FRAMWORK*******************

Q : what is ARRAY ?
Ans: ARRAY is an indexed collection of fixed number of homogeneous data element.
-------
Q what is ARRAY advantage ?
Ans -can represent multiple values by using single var.
---

Q what is Limitation of Object Type array:


--------------------------------
1-fixed size
2-hold only homogeneous data type element.
3-not impl on some standerd data structure so ready made support not availble.

------

Q what is ADVANTAGE OF COLLECTION .??


Ans
1- growable in nature.(based on our req we can increased or decreased size)
2- can hold both homo..and heterogenous type element.
3- implemented on some standerd data structure. so req method support is avaible.

COLLECTION: -
-----------
>if we want to (represnt a group of objects as a single entity) then we should go
for collection.
>collection defines several classes and interfaces to represent a group of objects
as a single entity.

*[ 9 MOST INTERFACES OF COLLECTION FW] :


========================================
1 Collection(i)
2 List(i)

3 Set(i)
4 SortedSet(i)
5 NavigableSet(i)

6 Queue

7 Map(i)
8 SortedMap(i)
9 NavigableMap(i)

[
Note:-
1-To represent a group of individual obects :-Collection, List, Set,
SortedSet, NavigableSet, Queue
2-To represent a group of key-value pairs :- map
]

1 Collection(i) [1.2]:
-----------------------
> It is root interface,
> It is used to represent a group of individual Objects as a single entity.
> it define Most common mehtods which are applicable for any collection.
Note: DIFF BW Collection(i) and Collections(c) :
==================================================
Collection(i): = > is a interface to represent a group of individual objects as a
single entity.
where as
Collections(c): => is an Utility classes present in java.util package to define
utillity methods for collection objects.

2 : List(i) [1.2v]:
===================
1- its child interface of collection interface.
2- duplicate are allowed
3- insertation order is preserved.
Note:- in 1.2v vector and stack classes are impl to impl List interface.

diag: Collection(i) [1.2]


|
List(i) [1.2]
|
-------------------------------------------------------
| | |
ArrayList(c) [1.2] LinkedList(c) [1.2] Vector(c)[1.2]
|
Stack(c)[1.2]

---------------------------

3 : Set(i) :
-------------

diag: Collection(i) [1.2]


|
Set(i) [1.2]
|
----------------------------------------------------------
| |
HashSet(c) [1.2] SortedSet(i) [1.2]
| |
LinkedHashSet(c) [1.4] NavigableSet(i) [1.6]
|
TreeSet(c) [1.2]

3 : Set(i) :
------------
>- child interface of collecion,
>- duplicate not allowed
>- insertion order not preserved(save in diff order)

4 : SortedSet(i):
-----------------
>- its child of Set interface
>- without duplicate but according to some sorting order.

5 : NavigableSet(i):
--------------------
>- child interface of SortedSet.
>- it Define several method for Navigation purpose.

-------------------------------------

6 : Queue(i) :
--------------

Collection(i) [1.2]
|
Queue(i) [1.5]
|
----------------------------------------------------------
| |
PriorityQueue(c) [1.5] BlockingQueue(c) [1.5]
|

--------------------------------------------
| |
PriorityBlockingQueue(c) [1.5]
LinkedBlockingQueue(c) [1.5]

6 : Queue(i) :
--------------
> child of interface colloection.
> used to represent obects (prior to processing).

[Note:-
1-To represent a group of individual obects :-Collection, List, Set,
SortedSet, NavigableSet, Queue
2-To represent a group of key-value pairs :- map
]

7 : Map(i) : diag
==========

Map(i) [1.2]
|

-----------------------------------------------------------------------------------
----Dictionary(AC) [1.0]
| | | |
|
HashMap(i) WeakHashMap(i) IdentityHashMap(i) SortedMap(i)[1.2]
Hashtable [1.0]
[1.2] [1.2] [1.4] |
|
NavigableMap(i) [1.6]
Properties [1.0]
|
TreeMap(i) [1.6]

7 : Map(i) :
-----------
>Note:-its not child of any collection interface.
>used to represent a group of object as Key-value pairs
>duplicate key not allowed but value can be duplicate.

8 : SortedMap(i) :
------------------
> its child of Map interface
> used to represent group of objects as Key-value with some sorting order.
> sorting based on key but not based on value.

9 : NavigableMap(i) :
---------------------
its child of SortedMap
>it define several method for navigation purpose.

-----------------------------------------------------------------------------------
-------

** LEGACY CLASSES (MEANS THAT COMES IN 1.0) FOR FW:


===================================================
1 : Enumeration (i)
2 : Dictionary (AC)
3 : Vector (Concrete class)
4 : Stack (Concrete class)
5 : Hashtable (Concrete class)
6 : Properties (Concrete class)

** Utility Classes:
--------------------
1 Collections
2 Array

** Cursors:
-----------
1 Enumeration (i)
2 Iterator (i)
3 ListIterator (i)

** Sortings:
------------
1 Comparable (1)
2 Comparator (i)

-----------------------------------------------------------------------------------
-------------------------------------------

** 1-COLLECTION (I):
------------------
>used to represent a group of individual objects as a single entity.

** METHODS: -> which are applicable for any collection object.


-----------
1- boolean add(Object o)

2- boolean addAll(Collection c)

3- boolean remove(Object o)

4- boolean removeAll(Collection c)

5- boolean retainAll(Collection c) : ->to remove all obj except peresent in c.

6- void clear()

7- boolean contains(Object o)

8- boolean containsAll(Collection c)

9- boolean isEmpty()

10- int size()

11- Object[] toArray()

12 Iterator iterator()

*Note:- no concrete class can impl collection interface directally.


no direct mehtod in collection interface to get Object direct.

-------------------------

2- List(I):
-----------
>child of collection interface.
>duplicate allowed
>insertation order is preserved.
>index we can diff duplicates. or index play most imp role.
**METHOD :
----------
1- void add(int index, Object o)

2- boolean addAll(int index, Collection c)

3- Object get(int index)

4- Object remove(int index)

5- Object set(int index, Object new) : => to replace element at specific index
with provided object and return old object.

6- int indexOf(Object o) : return index of 1st occerance of o.

7- int lastIndexOf(Object o)

8- ListIterator listIterator()

** 2.1 * ARRAYLIST(I):
----------------------
**IMP-NOTE:-ARRAYLIST best sutaible for retrival operations but
worst case if our operation is insertation or deletation in middile.(it
req several shift operation).
>underlying data structure for arraylist is "resizable array or growable array".
>duplicate allowed.
>insertion order is preserved.
>Heterogenous obj are allowed.
>null allowed.
*Note:- Except TreeSet and TreeMap everwhere heterogenuous object are allowed.

* CONSTRUCTORS:
---------------
1: ArrayList l = new ArrayList();
------------------------------------
> create empty object with default initial capacity 10.

Q- HOW ARRAYLIST IS GROWABLE ?


Note:- if arraylist reach its max capacity then a new arraylist object will be
created with

New Capacity = (Current Capacity *3/2)+1

2: ArrayList l = new ArrayList(initialCapacity);


---------------------------------------------------
> create empty object with specified initial capacity.

3: ArrayList l = new ArrayList(Collection c);


-------------------------------------------------
> create equalent object for given collection.

**Note:- we can use collection to hold and transfer Data (Objects) from one
location to Another location,
so to this collection class impl "Serializable" interface and "Clonable"
interfaces.
**Note:- ArrayList and Vector classes impl RandomAccess (is a marker interface
present in -java.util) Interface.(to access any random element with same
speed)

ex: how to check:


System.out.println(al instanceof Serializable); // true
System.out.println(al instanceof RandomAccess); // false

**IMP-NOTE:-ARRAYLIST best sutaible for retrival operations

** DIFF BW
----------
ARRAYLIST VECTOR
-----------------------------------------------------------------------------------
--
1- every method inside arraylist is- non syncronized 1- syncronized

2- at a time- multithread allowed- so it is not thread safe. 2- thread safe

3- prformance is high 3- low-


becouse of thread waiting.

4- introduced in 1.2 4- introduced


in 1.0 (its legacy)

-----------------------------------------------------------------------------------
---

Q-HOW TO GET SYNCRONIZED ARRAYLIST OBJECT ?


-------------------------------------------
ANS:-using syncronizedList(List l) method of (Collections class).

ex: public static List syncronizedList(List l)


ex:

ArrayList al = New ArrayList();


List l = Collections.syncronizedList(al);

GET SYNCRONIZED SET OBJECT ?


----------------------------------
ex: public static Set syncronizedSet(Set s)

GET SYNCRONIZED MAP OBJECT ?


----------------------------
ex: public static MAP syncronizedMap(Map m)

**IMP-NOTE:-ARRAYLIST best sutaible for retrival operations but


worst case if our operation is insertation or deletation in middile.(it
req several shift operation).

-----------------------------------------------------------------------------------
------------------------------

** 2.2 ** LinkedList:
---------------------
Note:-Best choice for our operation is - insertation or deletation in midile. but
worst choice for :- retrival.
>underlying data structur is "Double LinkedList"
>insertation order is preserved
>duplicate allowed
>hetero..obj is allowed.
>null is possible.

Note:- impl Serializable and Clonable interface but not RandomAccess interface.

** CONSTRUCTOR:
----------------

1: LinkedList l = new LinkedList();

2: LinkedList l = new LinkedList(Collection c);

** METHOD:
-----------
1 void addFirst(Object o)

2 void addLast(Object o)

3 Object getFirst()

4 Object getLast();

5 Object removeFirst()

6 Object removeLast()
---------------------------------------------------------------

** 2.3: ** VECTOR: [Every Method Syncronized]


-------------------
>Note:-best choice if our operation is retrival
but worst if our operation is insertation or deletation in midile.
>data structure is resizable or growable array.
>insertion order is preserved.
>duplicate allowed.
>null insertation is possible.
>impl Serializable, Clonable, and RandomAccess interface.
>vector is tread safe.->Every Method Syncronized inside vector.
** CONSTRUCTOR :
----------------
1 : Vector v = new Vector();
------------------------------
create- empty vector obj with default value 10.
after reaches its max capacity new vector created with
ex: new capacity= current capacity*2

2 : Vector v = new Vector(initialcapacity);


---------------------------------------------

3 : Vector v = new Vector(int initialcapacity, int incrementalcapacity);


--------------------------------------------------------------------------

4 : Vector v = new Vector(Collection c);


------------------------------------------

** METHOD:
----------

**To Add

1: add(Object o) -> Collection


2: add(int index, Object o) -> List
3: addElement(Object o) -> vector

**To remove:

1: remove(Object o) -> collection


2: removeElement(Object o) -> vector
3: remove(int index) -> List
4: removeElement(int index) -> vector
5: clear() -> Collection
6: removeAllElement() -> vector

**To Retrive Elements:

1: Object get(int index) - > List


2: Object elementAt(int index) -> vector
3: Object firstElement() -> vector
4: Object lastElement() -> vector

** OTHER IMP METHOD:


--------------------
int size()
int capacity()
Enumeration element()
------------------------------------------

** 2.3.1 ** STACK :
-----------------------
> its child of vector.
> specially designed for LIFO order.

*CONSTRUCTOR:
------------
ex: Stack s = new Stack();

** METHOD:
----------
1: Object push(Object o) => to insert object

2: Object pop() => to remove and return top of stack

3: Object peek() => to return top of stack without removel

4: boolean empty()

5: int search(Object o) => return offset (index number) if availble , else return
-1.

-----------------------------------------------------------------------------------
----

** 3 CURSORS OF JAVA:
---------------------
CORSOR:- to get objects one by one from collection we use cursors.

1: Enumeration
2: Iterator
3: ListIterator

1: Enumeration:
---------------
> we get Enumeration by using "element()" method of vector class.
Ex: Enumeration e = v.element(); // v is a vector class var.

**METHODS:
----------
1: Public boolean hasMoreElement();
2: public Object nextElement();

** LIMITATION OF ENUMERATION:
-----------------------------
1 - applicable only for legacy classes, not for all univarsally .
2- we can perform only Read operation. but not perform remove.

go for Iterator.

-------------------------------
**2: Iterator : [any colloction + Read and Remove]
---------------
> to get object one by one from collection.
> used for any collection object, means its universal.
> iterator can perform Read and Remove operations.
> we create object using iterator() method of Collection interface.

ex: Iterator itr = c.iterator(); => c is any collection object.

** METHODS:
-----------
1: public boolean hasNext()
2: public boolean next()
3: public void remove()

** Iterator Limitation:
-----------------------
1: single directional:->we can only move forword direction but not backword
direction.
2: Cant perform New object addition and replacing existing objects.
we can perform only read and remove not adition of new and replacing .

so go for ListIterator.
------------------------

** 3: ListIterator:
-------------------
>child interface of Iterator
>work Bi-Directional.(backword or forword)
> also can perform addition of new object and replacing existing objects.with read
and remove.
> we can get ListIterator obj by using listIterator();

ex: public ListIterator listIterator();

ex: ListIterator itr = l.listIterator(); = l is list Object.

** METHOD: [ListIterator define 9 metheds]


--------------------------------------------

** Forword Direction Method:

1 public boolean hasNext();


2 public Object next();
3 public int nextIndex();

** Backword Direction Method:

1 public boolean hasPrevious();


2 public Object previous();
3 public int previousIndex();
*OTHER:
Public void remove();
public void set(Object new);
public void add(Object new);

Note:
** Limitation of ListIterator:
> its used for only for list objects

-------------------------------------

COMPARISON OF CURSORS:
---------------------

PROPERTY ENUMERATTION ITERATOR


LISTITERATOR
-----------------------------------------------------------------------------------
------------------------------------
applicable for | only for legacy classes | any collection objects |
only for List objects
-----------------------------------------------------------------------------------
---------------------------------------------
Movement | only forword | only forword |
Bi-Directional
-----------------------------------------------------------------------------------
----------------------------------------------
How to Get | element() of Vector class | iterator() of Collection(I) |
listIterator() of List(I)
-----------------------------------------------------------------------------------
-----------------------------------------------
Accessability | Only Read | Read and Remove |
Read, Remove, Replace and Add New object.
-----------------------------------------------------------------------------------
------------------------------------------------
Method | hasMoreElements() | hasNext() | 9
methods
nextElement() next()
remove()
-----------------------------------------------------------------------------------
-----------------------------------------------
Is it legacy | yes 1.0v | No 1.2v |
No 1.2 v
-----------------------------------------------------------------------------------
------------------------------------------------
** 3 :Set(I) [duplicate not allowed and order not preserved]
--------------
> set is child interface of Collection(I)
> duplicate not allowed and order is not preserved.
Note:- Set(I) interface do not contains any methods and it use Colleciton interface
methods.

Collection(i) [1.2]
|
Set(i) [1.2]
|
----------------------------------------------------------
| |
HashSet(c) [1.2] SortedSet(i) [1.2]
| |
LinkedHashSet(c) [1.4] NavigableSet(i) [1.6]
|
TreeSet(c) [1.2]

**3.1: HashSet: (for search operation)


---------------
>underlying datastructur is Hashtable.
>insertation order is not preserved and it is based on hashCode of Obects.
>Duplicate are not allowed . if we are trying then no CE, RE, only get boolean
False Return.
>Null insertion is allowed.
>Heterogenous objects are allowed.
Note:=> HashSet impl Serializable and Clonable interface but not RandomAccess.

>Best for search operation.

**CONSTRUCTOR: [default fill ratio : 0.75]


--------------

1: HashSet hs = new HashSet();


-------------------------------
=> create empty hashset objects with default initialcapacity 16.
Note:- if its reach its 75 % capacity then create new hashset objects.

2: HashSet hs = new HashSet(initialcapacity); //=> after that it use ratio 0.75


---------------------------------------------

3: HashSet hs = new HashSet(int initialcapacity, float fillratio);


-----------------------------------------------------------------

4: HashSet hs = new HashSet(Collection c);


------------------------------------------

Q-what load factor ?


ans: fill ratio 0.75 means after filling 75% automatically a new HashSet object
will be created.
**imp-Note:-
In generally, we use LinkedHashSet and LinkedHashMap to develop Cache based
applications
where
Duplicate not allowed and insertation order must be preserved.

**3.1.1 : LinkedHashSet: [imp]


=======================
> its child class of hashset
> underlying data structur is combination of LinkedList and Hashtable.
> insertation order is preserved
> Duplicate are not allowed . if we are trying then no CE, RE, only get False
Return.
> Null insertation is allowed.
> Heterogenous objects are allowed.
Note:=> HashSet impl Serializable and Clonable interface but not RandomAccess.
> Best for search operation.
> it is exactally same as HashSet except following diff.

diff :

HashSet
LinkedHashSet
-----------------------------------------------------------------------------------
--------------------------------
1- use data structur is Hashtable 1- underlying data
structur is combination of LinkedList and Hashtable.
2- insertation order is not preserved 2- insertation order is
preserved.
3- introduced in 1.2v 3- introduced in 1.4v
-----------------------------------------------------------------------------------
---------------------------------

**imp-Note:-
In generally, we use LinkedHashSet and LinkedHashMap to develop Cache based
applications
where
Duplicate not allowed and insertation order must be preserved.
-----------------------------------------------------------------------------------
-------

**3.2 : SortedSet(I):
----------------------
> it is child interface of Set(I).
> Duplicate not allowed.
> All Objects will be inserted According to some sorting order (Default Natural
Sorting or Customized sorting order).

Note :-For String objects default Natural sorting is Alphabetical Order.


For Number Default Natural sorting is Ascending Order.
** METHOD:
----------
1 Object first()

2 Object last()

3 SortedSetheadSet(Object obj)

4 SortedSettailSet(Object obj)

5 SortedSetsubSet(Object ob1, Object ob2)

6 Comparator comparator()
=> Returns Comparator object that Describes underlying Sorting technique.
if we are using Default Natural Sorting order then we will get null.

------------------------------------------------------------------------

**3.2.1 : TreeSet:
------------------
> underlying Data Structure is balanced Tree.
> insertation order is not preserved and it is based on some Sorting order.
> Heterogenous objects are not allowed, if we are trying then we will get RE-
ClassCastException.
> null Insertion is allow (Only Once)
IMP NOTE:-> impl Serializable and Clonable interfaces but not RandomAccess
interface.

** CONSTRUCTOR:
---------------
1 TreeSet t = new TreeSet();
-----------------------------
=> Creates an Empty TreeSet object where all Element will be inserted according to
default Natural Sorting order.

2 TreeSet t = new TreeSet(Comparator c);


----------------------------------------
=> Creates an empty TreeSet object where element will be inserted according to
Customized Sorting order which is described by
Comparator Object.

3 TreeSet t = new TreeSet(Collection c);


----------------------------------------
4 TreeSet t = new TreeSet(SortedSet s);
---------------------------------------

Null acceptance:-
----------------
>for empty treeset as first element null insertion is possible. but after null if
we insert other null then get NullPointerException.
>for empty treeset if try null then get -NullPointerException.

Note:=>
Comparable :-
-------------
>a object is said to be Comparable only if corresponding class implements
Comparable interface.
ex:=> All Wrapper classes, String Class already implements Comparable interface.

> if we depend on Default Natural sorting order then Objects should be Homogenous
and Comparable. else get-ClassCastException

Note:
Comparable Interface present in java.lang package its contains only one method :- >

1 compareTo()

ex: public int compareTo(Object o)

ex: ob1.compareTo(ob2);
returns:
=> [-]minus if obj1 come befor obj2
=> [+]plus if obj1 come after obj2
=> [0]zero if obj1 and obj2 are equal.

ex:
sop("A".compareTo("Z")); //=> -25
sop("Z".compareTo("K")); //=> 15
sop("Z".compareTo("Z")); //=> 0

Note:- if we depend on Default natural sorting order and if try to insert element
then internally jvm call to "compareTo()" to identify sorting order.

**COMPARATOR(I):- If are not satisfied with default natural sorting order or


Natural sorting order is not availble then we can define our own
sorting by using Comparator Object.

Comparable :- for Natural sorting order.


Comparator:- for customized (our own) sorting order.

Note: Comparator(I) interface present in java.util package.

**Method: [2 methods]
---------
1- compare()
and
2- equals()

ex: public int compare(Object obj1, Object obj2)


------------------------------------------------
returns: [-] if obj1 come to befor obj2
[+] if obj1 come to after obj2
[0] if obj1 and obj2 are equals.

ex: public boolean equals(Object o)


-----------------------------------
Note:- if we are implementing Comparator Interface then compulsory we should
provide implementation for compare() method.
but
equals() is optional. because its already availble from object class through
inheritance.

Q- When we go for Comparable and When we go for Comparator ?


or
Comparable Vs Comparator ?
ans:
1: For pre defined Comparable classes like String,wrapper classes,By Default
natural sorting order is already availble.
if we are not satisfied then we can define our own sorting by Comparator object.

2: For pre define non comparable classes like StringBuffer , by Default sorting
order is not already availble.
so if we want to define our own sorting then we can use comparator object.

3: For our own classes lik Employee , the person who is writing Employee class he
is responsible to define default natural sorting order by implementing
Comparable interface.

4: The person who is using our own class, if he is not satishfied with Natural
sorting order then he can define his own sorting by
using Comparator object.
but if he is satisfied with default natural sorting order then he can use
directaly our class.

-----------------------------------------------------------------------------------
--------------------------------------------

**diff bw
---------

Comparable Comparator
-----------------------------------------------------------------------------------
-------------------------------------
1 present in java.lang package. 1 present in
java.util package
2 its for Default natural sorting order. 2 its for
Customized (our own) sorting order.
3 define one method :-compareTo() 3 define 2
method :- compare() and equals().
4 all wrapper classes and String classes impl this interface 4 its only impl
classes are Collator and RuleBaseCollator.
-----------------------------------------------------------------------------------
--------------------------------------

** DIFF BW:
-----------

PROPERTY | HashSet | LinkedHashSet |


TreeSet
-----------------------------------------------------------------------------------
-----------------
data structur | Hashtable | Hashtable and LinkedList |
Balanced Tree

Insertion order | Not preserved | Preserved | Not


preserved

Sorting order | not applicable | not applicable |


applicable

Heterogenous Objects | allowed | allowed |


not allowed

Duplicate Objects | not allowed | not allwed |


not allowed

null acceptance | allowed (only once) | allowed (only once) |


for empty Treeset as first element null is
posible, but in other case we will get:-npe

-----------------------------------------------------------------------------------
--------------------------------------------

** MAP(I):
-----------

Map(i) [1.2]
|

-----------------------------------------------------------------------------------
----Dictionary(AC) [1.0]
| | | |
|
HashMap(i) WeakHashMap(i) IdentityHashMap(i) SortedMap(i)[1.2]
Hashtable [1.0]
[1.2] [1.2] [1.4] |
|
NavigableMap(i) [1.6]
Properties [1.0]
|
TreeMap(i) [1.6]

** MAP(I):
===========
> map is not child of collection.
> if we want to represent a group of objects as a key-vlaue pairs then go for Map.
> Both key and values are objects only.
> Imp:->Duplicate Key not allwed but values can be duplicated.

ENTRY:=> Each key and value pair is called Entry.


ex: 101 durga => is one entry.

**Methods:
----------
1 Object put(Object key, Object value);

2 void putAll(Map m);

3 Object get(Object key);

4 Object remove(Object key);

5 boolean containsKey(Object key);

6 boolean containsValue(Object value);

7 boolean isEmpty();

8 int size();

9 void clear();

** Collection view of Map

10 Set keySet();
11 Collection values();
12 Set entrySet()

Entry(I):
----------
>each key-value pair is called one entry.
>without existing map object , No chance of existing entry object.
so entry interface is define inside Map interface.

** HashMap:
-----------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)

** DIFF BW:

HashMap Hashtable
-----------------------------------------------------------------------------------
--------------------------------
1 no method is syncronized inside hashmap. 1 every method is
syncronized inside Hashtable.

2 Multiple treads are allowed so no tread safe 2 one tread


allowed so thread safe.
3 performance is high 3 performance is low.

4 null is allowed for both key and values 4 not allowed for
both key and values. get NPE.

5 introduced in 1.2 v 5 introduced in 1.1 , so it


is legacy.
-----------------------------------------------------------------------------------
--------------------------------

Q- How to get Syncronized Version of HashMap ?


ans: by using syncronizedMap() of Collections class.

*constructors:
--------------
1 HashMap m = new HashMap();
=> create an empty HashMap obj wiht default initial capacity 16 and default fill
ratio 0.75

2 HashMap m = new HashMap(int initialcapacity);

3 HashMap m = new HashMap(int initialcapacity,float fillratio);

4 HashMap m = new HashMap(Map m);

----------------------------------------------------------

** LinkedHashMap:
-----------------
> its child class of HashMap.
> Note:- insertion order is preserved.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)
> its exactally same as HashpMap except following differences

Diff BW:

HashMap LinkedHashMap
-----------------------------------------------------------------------------------
-------------------------------
1 underlying data structur is Hashtable. 1. combination of
Hashtable and LinkedList.
2 insertion not preserved 2. insertion order
is preserved.
3 introduced in 1.2v 3 introduced in 1.4v
-----------------------------------------------------------------------------------
--------------

Imp Note:
1: we can use LinkedHashSet and LinkedHashMap for developing Cache based apps
where Duplicate not allowed and insertion must be preserved.

**IdentityHashMap:
------------------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)
>exactally same as HashMap except following diff.
1 in HashMap jvm will use .equals() to identify duplicate keys, which mean for
content comparision.
but
in IdentityHashMap jvm will use == operator to identify duplicate keys, which is
mean for reference comparision.

Q-what is diff bw == operator and .equals();


ans:
== use for ref comparision.
whereas
.equals() for content comparision.

**WeakHashMap :
---------------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times).

>Exactally same as HashMap Except following Diff-

Note 1: in case of HashMap, Dominates Garbage Collector, that mean if Object does
not have any ref still it is not Eligible for
garbage collector it is associated with HashMap.

Note 2: but in case of WeakHashMap if an Object does not contain any ref then it is
always Eligible for GC even though it is associated with
WeakHashMap.
that mean Garbage collector Dominate WeakHashMap.
** SortedMap :
--------------
>its child interface of Map.
>it represent according some sorting order of keys.

METHODS:
--------
>SortedMap defines the following methods.

1 Object firstKey()
2 Object lastKey()
3 SortedMapheadMap(Object key)
4 SortedMaptailMap(Object key)
5 SortedMapsubMap(Object key1, Object key2)
6 Comparator comparator()

** TreeMap:
-----------
>underlying data structur is : Red Black Tree.
>duplicate keys are not allowed but values can be duplicate.
>insertion order is not presrved,
> its based on some sorting order of keys.
Note 1:- if we denpend on Default Natural Sorting Order then keys should be :
Homogenous and Comparable.
else we get RE-Class cast exception
Note 2:- if we define our own sorting by Comparator then Keys can be Heterogenous
and Non-Comparable.
but
There is no restriction on values, they can be Heterogenous and Non
Comparable.

*NULL ACCEPTANCE:
-----------------
>For empty TreeMap 1st entry with null key is allowed. but after that if we try
then get :-NPE.
>For non empty TreeMap if we try to insert null entry then get RE ->NPE
But There is no restrictions on null Values.

*CONSTRUCTOR:
-------------

1 TreeMap tm = new TreeMap() // for default natural sorting order

2 TreeMap tm = new TreeMap(Comparator c) // for customized sorting order.

3 TreeMap tm = new TreeMap(SortedMap m) // inter Conversion bw Map objects

4 TreeMap tm = new TreeMap(Map m);

**IMP PROG FOR CUSTOMIZED ORDER DESC :


public class TreeMapSortingDemo {

public static void main(String[] args) {


TreeMap tm = new TreeMap(new MyComparator());
/*tm.put("A",106);
tm.put("Z",101);
tm.put("B",104);
tm.put("Y",105);
tm.put("C",102);
tm.put("X",103); */

tm.put(103,"A");
tm.put(101,"B");
tm.put(102,"C");

System.out.println(tm);

}
class MyComparator implements Comparator{
public int compare(Object ob1, Object ob2)
{
String s1=ob1.toString();
String s2=ob2.toString();

return s2.compareTo(s1);

op:
{Z=101, Y=105, X=103, C=102, B=104, A=106}
{Z=101, Y=105, X=103, C=102, B=104, A=106,
and
103=A, 102=C, 101=B}

**Hashtable :
--------------
>underlying data structur for Hashtable is Hashtable only.
>Duplicate keys are not allowed. but values can be duplicate.
>insertion order is not preserved and its based on Hashcode of the keys.
>Heterogenous objects are allowed for both keys and values.
>null insertion is not posible for both key and values. we get :-NPE.

Note:-every method inside Hashtable is -syncronized so hashtable is tread safe.

*CONSTRUCTOR:
------------

1 Hashtable ht = new Hashtable()


=> create empty hashtable with default initialcapactiy 11 and default fill ratio :
0.75
2 Hashtable ht = new Hashtable(int initialcapactiy)

3 Hashtable ht = new Hashtable(int initialcapactiy, float fillratio)

4 Hashtable ht = new Hashtable(Map m)

** Properties:
==============
>it is child class of Hashtable.
use Properties Object to hold Properties which are comming from Properties File.
>if anything which changes frequently (like DB username, password, urls etc) never
Recommended to Hard Code in prog.
bcoz for every changes in source file we have to Recompile, Rebuild and
Redeploying apps and some times server restart also req.

* To Overcome this problum we have to Configur such type of Properties in


Properties File.
the main advantage of this approach is if there is a change in Properties file,
then to Reflect that changes just Redeployment is Enough.

>Properties can be used to represent a Group of key-value pairs where Both Key and
Value should be String Type.

**CONSTRUCTOR:
-------------

Properties p = new Properties()

*METHOD:
--------
1 public String getProperty(String pname); // to get value associated with
specific Property.

2 public String setProperty(String pname, String pvalue); // to set a new


property

3 Public Enumeration propertyName(); // it returns all Property Names

4 public void load(InputStream is); // to load properties from Properties file


into java Properties Object.

5 public void store(OutputStream os, String comment); // to store Properties


from java Properties Object into Properties file.

**Note: imp programe

1- first write one properties file and save with .properties extantion at project
level and insert data

paytm=bl123
username=123
bl=12345

2- write a prog to
read propeties
add
new propeties
ex:

package com.app.demo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

public class PropertiesDemo {

public static void main(String[] args) throws Exception {


Properties p = new Properties();

FileInputStream fis = new FileInputStream("ABC.properties");

p.load(fis); // read file from p file to p object

System.out.println(p); // print file data on console

String s=p.getProperty("userName");
String s1=p.getProperty("password");
System.out.println(s);
System.out.println(s1);

p.setProperty("yogesh","12345"); // set new properties to file


FileOutputStream fos = new FileOutputStream("ABC.properties");
p.store(fos,"Updated by BL"); // store data p obj into p file.

System.out.println(p);

}
}

------------------------

** 1.5 Version Enhancements


---------------------------

** Queue(I)
-------------
> Queue is a child interface of Collection.
> to represent a group of individual objects Prior to processing then we should go
for queue.
> from 1.5 v onwords LinkedList also impl Queue Interface.
> Queue follow FIFO (firsst in first out) order. but based on our req we can impl
our own Priorities(like - PriorityQueue)
> LinkedList based impl of Queue always follows FIFO order.

ex: Befor sending a Mail , we have to store all Mail using some data structure and
for the 1st inserted Mail ID should be sent
1st. for this Req queue is the best choice.

Method:
-------

1 boolean offer(Object o); // to add object into queue.

2 Object peek(); // to return head element of the queue.


// if queue is empty , it return null.

3 Object element(); // return head element of the queue.


// but if queue empty , RE- NoSuchElement found

4 Object poll(); // to remove and return head element of queue.


// if queue is Empty , return null.

5 Object remove(); // to remove and return Head element of the Queue.


// but if queue empty , RE- NoSuchElement found

** PriorityQueue:
-----------------
> this is a Data Structur which can be used to represent a group of individual
objects prior to processing according to some priority.
> Priority order may be either Default Natural sorting order or Customized sorting
order specified by Comparator Object.
> if we depend on Default Natural sorting order then Object should be Homogenous
and Comparator otherwise we get- classcastexception.
> Duplicate objects are not allowed.
> insertion order is not preserved and it is based on some priority.
> null not allowed , even 1st element also.

** Constructor:
---------------

1 PriorityQueue q = new PriorityQueue();


=> create an empty PriorityQueue with default initialcapacity 11 and
all object will be inserted according Default Natural sorting order

2 PriorityQueue q = new PriorityQueue(int initialcapacity);

3 PriorityQueue q = new PriorityQueue(int initialcapacity, Comparator c);

4 PriorityQueue q = new PriorityQueue(SortedSet s);

5 PriorityQueue q = new PriorityQueue(Collection c);


** 1.6 Version Enhancements
---------------------------

** NavigableSet(I)
-------------------
>it is child interface of SortedSet.

**Method:- it define several methods to navigation purpose.


---------
1 floor(e) ; // return highest element which is <= e.

2 lower(e); // return highest element which is <e.

3 ceiling(e); //return lowest element which is >= e.

4 higher(e); //return Highest element which is >e.

5 pollFirst(); //remove and return 1st element.

6 pollLast(); //remove and return last element.

7 descendingSet(); // it return navigableSet in reverse order.

** NavigableMap(I):
--------------------
> its child interface of SortedMap.

Method:
-------
1 floorKey(e) ; // return highest element which is <= e.

2 lowerKey(e); // return highest element which is <e.

3 ceilingKey(e); //return lowest element which is >= e.

4 higherKey(e); //return Highest element which is >e.

5 pollFirstEntry(); //remove and return 1st element.

6 pollLastEntry(); //remove and return last element.

7 descendingMap(); // it return navigableMap in reverse order.

** UTILITY CLASSES:
-------------------

* Collections
* Arrays

* Collections(C):
--------------------------------------------------
> Collections class is an utility class , present in java.util package to define
Utility Methods for Collection Objects.

**TO SORT ELEMENT OF LIST : [following methods are given]


--------------------------

1 public static void sort(List l);


----------------------------------
> it sort based on DNS order.
> in this case , List should contains only Homogenous and Comparable objects.
else get RE-classCast
> List should not contain null -else get NPE

ex: Collections.sort(al);

2 public static void sort(List l, Comparator c);


------------------------------------------------
> it is based on Customized sorting order.
ex: Collections.sort(al,new MyComparator());

**TO SEARCH ELEMENT OF LIST : [following methods are given]


--------------------------

1 public static int binarySearch(List l, Object target);


=> first we sorting List according to DNS order then we use this method.

ex:
Collections.sort(al);
System.out.println("BinarySearch :"+Collections.binarySearch(al, "C"));

2 public static int binarySearch(List l, Object target, Comparator c);


=> first we sorting according to customized (Comparator) then use this mehtod.
ex:
Collections.sort(al,new MyComparator());
System.out.println("BinarySearch :"+Collections.binarySearch(al, "C", new
MyComparator()));

**CONCLUSION:
-------------
>internally the above search methods will use Binary Search Algorithm.
>Befor search operation , compulsory List should be Sorted. else get unpredictable
result.
>success search return Index.
>unseccess search return Insertion point.
Insertion point:- its a location where we can insert the target element in sorted
list.

> if list is sorted according to Comparable then at the time of search operation we
should pass same comparator object. else we get
unpredicatble result.

**TO REVERSE ELEMENT OF LIST : [following methed are given]


--------------------------

1 public void reverse(List l);

2 reverseOrder();

** reverse() Vs reverseOrder():
==================================
1 reverse() :=> to reverse order of elements of list.

2 reverseOrder() :=> to get reverse Comparator.


ex: Comparator c1 = Collections.reverseOrder(Comparator c);

-----------------------------------------------------------------------------------
-----------

** ARRAYS:
-----------
>Arrays class is an Utility class to define several utility methods for Array
Objects.

** SORTING ELEMENTT OF ARRAY:


-----------------------------

1 public static void sort(primitive[] p); // To Sort according to Natural Sorting


order.

2 public static void sort(Object[] o); // to Sort according to Natural Sorting


order.

3 public static void sort(Object[] o, Comparator c); // to sort according to


customized sorting order.

*Note:- Object[] type array, we can sort to Natural sorting or Customized sorting
order.
but
Primitive[] only based on Natural sorting.

Ex: Arrays.sort(str);

Arrays.sort(str, new MyComparator());


** SEARCH ELEMENTT OF ARRAY:
----------------------------

1 public static int binarySearch(primitive[] p, primitive target);


=>primitive array Sorted according to Natural Sorting order.

2 public static int binarySearch(Object[] o, Object target);


=>if Object array Sorted according to Natural Sorting order then use this.

3 public static int binarySearch(Object[] o, Object target, Comparator c);


=>if Object array Sorted according to Comparator then use this.

Note: all rules of arrays class binarySearch() are exactally same as Collections
class binarySearch()

ex: Arrays.sort(s); // s is a string[]


Arrays.sort(s,new MyComparator());

sop(binarySearch(s,"A", new MyComparator()));

---------------------------

** CONVERSION OF ARRAY TO LIST:


--------------------------------
1 public static List asList(Object[] ob)

Note=> Arrays class contains asList() for this converting array to list.

IMP note:- but this method will not create an indepedent List Object, just we view
array in list form.
if we perform any changes autmatically that will be reflect to List
ref.
similarly by using List ref if perform any changes automatically change
will reflect to array.

Note: - using list ref if we try to perform any operations add, remove which diff
the size then get RE- unsupportedOperation.

Ex: List l = Arrays.asList(s); // s is an String[] s;

-----------------------------------------------------------------------------------
-----

** CONCURRENT-COLLECTIONS[1.5]**** [Note - see all programm example with this


notes. how to use]
===================================
Q** NEED OF CONCURRENT COLLECTIONS:
----------------------------------
CASE 1: in tradition collection can be accessed by multiple thread so there may
be chance of data incosistancy prob,
so these are not thread safe.

CASE 2: and in case of already existed thread safe collection[vector, Hashtable,


syncronizedList(), syncronizedSet(). syncronizedMap()] are
performance wise not good. or total collection will be loaded by only one thread
at a time and it increase waiting time of tread.

CASE 3: Other problum, while one thread iterating collection, then other threads
are not allowed to modify collection object simultanculy.
so
Finally , Traditional Collection object are not sutaible for scalable multi
threaded applications.

** Concurrent collections :
---------------------------
1 Concurrent collections are thread safe
2 performance is more because of diff Locking Mechanism.
3 while one thread interacting collection the other thread allowed to modify
collection in safe manner.

** IMPORTANT CONCURRENT CLASSES ARE:


====================================

1 ConcurrentHashMap
2 CopyOnWriteArrayList
3 ColyOnWriteArraySet

** ConcurrentMap(C):
--------------------
Map(I):
|
ConcurrentMap(I)
|
ConcurrentHashMap(C):

ConcurrentMap(I) METHOD: -> it define following 3 specific mehtods


------------------------

1 Object putIfAbsent(Object key, Object value)


=> to add entry to map if specified key is not already avaible.

DIFF BW
-------
put() putIfAbsent()
-----------------------------------------------------------------------------------
-------------------------------------
> if key is not avaible, old vlaue will replaced with new value and retrurn old
value
> if key is already
present then entry will not be added and return old
associated value.
if key is not availble then only
entry will be added.

2 Object remove(Object key, Object value)


=> remove entry if key associted with specified value only.

3 Object replace(Object key, Object oldvalue, Object newValue)


=> if the key value matched then replaced with newvalue

-------------

*****ConcurrentHashMap(C):
==========================
> underlying data structur is Hashtable
>ConcurrentHashMap allows Concurrent Read and Thread safe update operations.
to perform Read operation thread will not require any Lock. but
to perform update operation thread requires Lock but it is lock of a perticular
part of Map.
Note:- instead of whole Map concurrent update achived by internally dividing Map
into smaller Portion which is defined by
Concurrency Level.

> the default concurrency level is 16.


Note:- that is ConcurrentHashMap allows simultanceous Read operation and
simultancously 16 Write(Update) operations.
> null is not allowed for both Keys and Values.

Note:- while one thread iterating , the other thread can perform update operation
and ConcurrentHashMap never threw ConcurrentModificationException

** CONSTRUCTORS:
===============

1 ConcurrentHashMap m = new ConcurrentHashMap();


------------------------------------------------
=> create empty ConcurrentHashMap with default initialcapacity 16 and default
FillRatio 0.75 and default Concurrency Level 16

2 ConcurrentHashMap m = new ConcurrentHashMap(int initialcapacity );


--------------------------------------------------------------------

3 ConcurrentHashMap m = new ConcurrentHashMap(int initialcapacity, float


fillRatio );
-----------------------------------------------------------------------------------
--
4 ConcurrentHashMap m = new ConcurrentHashMap(int initialcapacity , float fillRatio
, int concurrencyLevel);
-----------------------------------------------------------------------------------
------------------------

5 ConcurrentHashMap m = new ConcurrentHashMap(Map m);


-----------------------------------------------------

** DIFF BW:

HashMap ConcurrentHashMap
-----------------------------------------------------------------------------------
---------------------------------------
1 not thread safe 1 thread safe
2 performance is high, not req to thread wait 2 performance is low, req
to thread wait.
3 while one thread iterating , other thread not allowed to modity.
3 while one thread iterating , other
thread allowed to modity.

4 Iterator of HashMap is Fail-Fast and its throws ConcurrentModificationException.


4 Iterator of ConcurrentHashMap is Fail-
Safe and its will not throws
ConcurrentModificationException.

5 null is allowed for both keys and values 5 null is not allowed for
both keys and values-get=>NPE

6 introduce in 1.2 v 6 introduce in 1.5 v

-----------------------------------------------------------------------------------
--------------------------------------

** DIFF BW:

ConcurrentHashMap syncronizedMap()
Hashtable
-----------------------------------------------------------------------------------
-------------------------------------------
1 get Thread safety without locking total Map | 1 get tread safety by whole Map
object | 1 get tread safety by whole Map object

2 at a time multi threads are allowed in sage manner |2 at a time one threads are
allowed |2 at a time one threads are allowed
3 read operation can be perform without lock but write operation with bucket level
lock
| 3 Read and Write operation req
total Map object Lock.
| 3 Read and Write
operation req total Map
object Lock.

4 while one thread iterating Map , other thread allowed to modify map
| 4 while one thread iterating Map , other thread
not allowed to modify map get-ConModiEe
|4 while one thread
iterating Map , other thread
not allowed to modify map

5 Iterator is Fail-safe so wil not raise ConModi.Ex..


| 5 Iterator is Fail-Fast so will raise ConModi.Ex..
|5 Iterator is Fail-safe
so wil not raise
ConModi.Ex..

6 null is not allowed for both key and value


| 6 null allowed for both key and value
| 6 null is not allowed
for both key and value

7 introduced in 1.5v |7 introduced in 1.2v | 7


introduced in 1.0v
-----------------------------------------------------------------------------------
---------------------------------------

** CopyOnWriteArrayList(C):
============================
Collection(I)
|
List(I)
|
CopyOnWriteArrayList(C):

CopyOnWriteArrayList(C):
------------------------
> it is thread safe of ArrayList , as the name indicate CopyOnWriteArrayList create
a cloned copy of underlying ArrayList for update operation at certain point both
will Syncronized automatically which is taken care by JVM internally.

> update operatin on clone copy there is no effect for thread which performs read
operation
Note:- it is costaly because for every update a cloned copy will be created.
so CopyOnWriteArrayList() is best choice if several Read operations and less
Number write operations are required.

> Insertion order is preserved.


> Duplicate objects are allowed.
> Heterogenous objects are allowed.
> Null is possible.

>It impl Serializable , Clonable , and RandomAccess interfaces.

Note:- while one thread Iterating CopyOnWriteArrayList , other threads allowed to


modified and will not get-ConMod.exc..
mean that is Iterator is Fail-Safe.

> Iterator of ArrayList can perform Remove operation but Iterator or


CopyOnWriteArrayList can not perform Remove operation.
get-UnsupportedOperationExc...

** CONSTRUCTOR:
===============

1 CopyOnWriteArrayList I = new CopyOnWriteArrayList();

2 CopyOnWriteArrayList I = new CopyOnWriteArrayList(Collection c);

3 CopyOnWriteArrayList I = new CopyOnWriteArrayList(Object[] a);


------------------------------------------------------------------------------

** Method:
==========
1 boolean addIfAbsent(Object o);
--------------------------------
=> element will be added if List do not contains this element.

2 int addAllAbsent(Collection c);


---------------------------------
=> elements of collection will added to list if elements are absent and returns
number of element added.

** DIFF BW:
===========

ArrayList CopyOnWriteArrayList
-----------------------------------------------------------------------------------
-------------------------------
1 not thread safe 1 its also not thread safe.

2 while one thread Iterating List object, the other thread not allowed to modified
2 while one thread Iterating List object, the
other thread allowed to modified

3 Iterator is Fail-Fail 3 Iterator is Fail-Safe.

4 Iterator of ArrayList can perform Remove operation 4 Iterator of


CopyOnWriteArrayList can not perform Remove operation

5 introduced in 1.2 v 5 introduced in 1.5 v


-----------------------------------------------------------------------------------
----------------------------

** DIFF BW:

CopyOnWriteArrayList SycronizedList()
vector()
-----------------------------------------------------------------------------------
-----------------------------------

1 Thread safety becouse every operation perform on saperate cloned copy.


1 get thread safety, can access one thread at a time.
1 will get Thread safety ,can
access one thread at a time.

2 at a time multi threads allowed 2 at a time only one thread allowed 2 at a


time one thread allowed

3 while one thread Iterating List, other thread are allowed to modify.
3 while one thread Iterating , other thread are not
allowed to modify.
3 while one thread
Iterating, other thread are
not allowed to modify.

4 Iterator is Fail-Safe ,will not raise con.modi..exc.


4 Iterator is Fail-Fast, will raise con.modi..exc.
4 Iterator is Fail-Fast,
will raise con.modi..exc.

5 Iterator can not perform Remove operations.


5 Iterator can perform Remove operations.
5 Iterator can not
perform Remove operations.

6 introduced in 1.5 v 6 introduced in 1.2 v 6 introduced


in 1.0 v

-----------------------------------------------------------------------------------
--------------------------------------
** CopyOnWriteArraySet :
========================
Collection(I)
|
Set(I)
|
CopyOnWriteArraySet(C)

CopyOnWriteArraySet:
--------------------
> it is thread safe version of Set.
> internally implemented by CopyOnWriteArrayList.
> insertion order is preserved.
> Duplicate object not allowed.
> Multiple threads can perform Read operation simultanciouly but for every update
operation a seprate cloned copy will be created.
which is costaly so if multiple update operation are required then its not
recommended CopyOnWriteArraySet.
> while one thread iterating Set the other threads allowed to modify set , not get
Con.modi.exc,,
> Iterator of CopyOnWriteArraySet can perform only Read operation and will not
perform remove operation.-get not supported exc..

** CONSTRUCTOR:
---------------

1 CopyOnWriteArraySet s = new CopyOnWriteArraySet();

2 CopyOnWriteArraySet s = new CopyOnWriteArraySet(Collection c);

** METHODS: => whatever methods present in Colleciton and Set interface are only
Methods applicable for CopyOnWriteArraySet
there are no special mehtods.

** DIFF BW:
-----------
CopyOnWriteArraySet syncronizedSet()
-----------------------------------------------------------------------------------
------------------------------------
1 it is thread safe-update op performed on seprate cloned copy. 1 it is
thread safe

2 while one thread Iterating Set, other thread are allowed to modify.
2 while one thread Iterating, other
thread are not allowed to modify.

3 Iterator is Fail-Safe. 3 Iterator is Fail-Fast.

4 Iterator can perform only Read operation can not perform Remove operation.
4 Iterator can perform only Read operation can
not perform Remove operation.

5 introduced in 1.5 v 5 introduced in 1.7 v

-----------------------------------------------------------------------------------
-----------------------------------------

** Fail-Fast Vs Fail-Safe Iterators:


-------------------------------------

Fail-Fast Iterators:-
--------------------
while one thread iterating Collection , and if other thread try to perform
Structural modification to underlying collection,
then immediatally Iterator Fails by raising ConcurrentModificationException. such
Iterator called-Fail-Fast Iterators.

Fail-Safe Iterators:-
----------------------
while one thread iterating Collection , and if other thread allowed to perform any
Structural modification to underlying collection, such Iterator called-Fail-Safe
Iterators.

Fail-Safe Iterators will not raising ConcurrentModificationException,bcoz every


update operation will be perform on seprate cloned copy.

** DIFF BW: Fail-Fast Vs Fail-Safe Iterators


-----------

PROPERTIES FAIL-FAST FAIL-SAFE


-----------------------------------------------------------------------------------
-------------------------------------
1-does it through- ConcurrentModificationException| yes
| No

2 is the cloned copy will be created | No | yes

3 Memory Problum | No | yes

4 Examples | ArrayList, Vector, HashMap, HashSet | 1-


ConcurrentHashMap,
2-
CopyOnWriteArrayList,
3-
CopyOnWriteArraySet,

-----------------------------------------------------------------------------------
----------------------------------------

** ENUM WITH COLLECTIONS:


-------------------------
Collection(I)
|
Set(I)
|
EnumSet(AC) [1.5v]
|
----------------------------------
| |
RugularEnumSet JumboEnumSet

** EnumSet:
-----------
> it is specially designed Set implemented Collection applicable only for Enum.
> introduced in 1.5 v.
> EnumSet is internally impl as Bit Vectors which improve performance.
> performance is very high, if we want ot store Enum constants than traditional
collecitons(like HashSet, LinkedHashSet)
> All elements of EnumSet should be same Enum Type only, if we trying to add diff
enums get CE.
> Iterator Returned by EnumSet is Traverse, Iterate elements in their Natural
order(order in which they declared).
> inside EnumSet we can not add null. else get NPE.
> EnumSet is an abstract class so we can not create object directaly.
> EnumSet define several Factory Method to create Enum Object.

>EnumSet define 2 child class


1 RegularEnumSet
2 JumboEnumSet

> the Factory method will return this class internally based on Size ,
if size< 61 then RegularEnumSet else if size >64 then JumboEnumSet choosed.
** EnumMap
==========
> specially designed map to use Enum type objects as Keys.
> introduced in 1.5 v
> EnumMap implements Serializable and Clonable interfaces.
> EnumMap is internally impl as Bit Vectors[Arrays] which improve performance.
> performance is very high, if we want ot store Enum constants than traditional
collecitons(like HashMap)..
> all keys to EnumMap should be from a single Enum , if we try to use diff get CE.
so EnumMap is type safe.
> it never throw ConcurrntModi..exc.

> Iterator of EnumMap iterate elements according to Ordinal value of Enum Keys(in
order enum constant are declared in same order only iteratored.).
>null key is not allowed. else get NPE.

** CONSTRUCTOR:
---------------

1 EnumMap m = new EnumMap(Class KeyType);


empty enummap with specified key type

2 EnumMap m = new EnumMap(EnumMap m);


enummap with same key type and specified EnumMap . internally containing same
mapping.

3 EnumMap m = new EnumMap(Map m);


to create and equivalent EnumMap for given Map.

** METHODS:- [does not containing any new mehtods , use general Map mehtods only]

-----------------------------------------------------------------------------------
---------------------------

** OVERVIEW OF JAVA QUEUES:


---------------------------
Collection(i)
|
Queue(I) [1.5]
|
-----------------------------------------------------------------------
-----
| | |
PriorityQueue[1.5v] BlockingQueue[1.5v]
TransferQueue[1.7v]

Queue:
-------
>To represent a group of individual objects Prior to processing .
>Queue is child interface of Collection

PriorityQueue:
--------------
> it is implemented Class of Queue.
>if we want to represent a group of individual objects Prior to processing
according to priority then use this .

BlockingQueue:
--------------
> it is child interface of Queue. present in java.util.Concurrent package.
> it is thread safe collection.
> it is specially designed not to store element but also support Flow control by
Blocking Mechanism.
> if Queue is empty take() (retrivel operation) will be Blocked until Queue will be
updated with items.
> put() will be blocked if Queue is full untill space availbility.
> this property makes BlockingQueue best choice for produce consumer problum. when
one thread producing items to the queue and other thread consuming items from
queue.

-----------------------------------------------------

** Transfer Queue:
------------------
> in BlockingQueue we can only put elements into the Queue and if only Queue is
full then our put() will be blocked until space is
avaible.
> but in TransferQueue we can also block until other thread reciving our element.
so this is the behivour of transfer().
In BlockingQueue we are not required to wait other threads recive our element but
in transferQueue we have to wait until some other thread recive our element.
> TransferQueue is the best choice for Message passing application where guarantee
for the Delivery.
Collection(I)
|
Queue(I) [1.5v]
|
Deque(I) [1.7v]

Deque(I):
---------
>it represent a Queue where we can insert and remove elements from Deque, Both Ends
of Queue.
Deque mean Double Ended Queue.

BlockingDeque(I) [1.6v]
-----------------------:
> its the Child interface of BlockingQueue and Deque.
> it simple Deque with blocking operations but wait for the Deque to become non
empty for retrieval operation and wait for space to store element.

-----------------------------------------------------------------------------------
--------------------------------

You might also like