Collection Basic Questions and Answer
Collection Basic Questions and Answer
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.
---
------
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.
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.
---------------------------
3 : Set(i) :
-------------
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.
-----------------------------------------------------------------------------------
-------
** 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.
2- boolean addAll(Collection c)
3- boolean remove(Object o)
4- boolean removeAll(Collection c)
6- void clear()
7- boolean contains(Object o)
8- boolean containsAll(Collection c)
9- boolean isEmpty()
12 Iterator iterator()
-------------------------
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)
5- Object set(int index, Object new) : => to replace element at specific index
with provided object and return old object.
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.
**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)
** DIFF BW
----------
ARRAYLIST VECTOR
-----------------------------------------------------------------------------------
--
1- every method inside arraylist is- non syncronized 1- syncronized
-----------------------------------------------------------------------------------
---
-----------------------------------------------------------------------------------
------------------------------
** 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:
----------------
** METHOD:
-----------
1 void addFirst(Object o)
2 void addLast(Object o)
3 Object getFirst()
4 Object getLast();
5 Object removeFirst()
6 Object removeLast()
---------------------------------------------------------------
** METHOD:
----------
**To Add
**To remove:
** 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
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.
** 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();
Note:
** Limitation of ListIterator:
> its used for only for list objects
-------------------------------------
COMPARISON OF CURSORS:
---------------------
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]
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).
2 Object last()
3 SortedSetheadSet(Object obj)
4 SortedSettailSet(Object obj)
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.
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: 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.
**Method: [2 methods]
---------
1- compare()
and
2- equals()
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:
-----------
-----------------------------------------------------------------------------------
--------------------------------------------
** 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.
**Methods:
----------
1 Object put(Object key, Object value);
7 boolean isEmpty();
8 int size();
9 void clear();
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.
4 null is allowed for both key and values 4 not allowed for
both key and values. get NPE.
*constructors:
--------------
1 HashMap m = new HashMap();
=> create an empty HashMap obj wiht default initial capacity 16 and default fill
ratio 0.75
----------------------------------------------------------
** 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.
**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).
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:
-------------
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.
*CONSTRUCTOR:
------------
** 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.
>Properties can be used to represent a Group of key-value pairs where Both Key and
Value should be String Type.
**CONSTRUCTOR:
-------------
*METHOD:
--------
1 public String getProperty(String pname); // to get value associated with
specific Property.
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;
String s=p.getProperty("userName");
String s1=p.getProperty("password");
System.out.println(s);
System.out.println(s1);
System.out.println(p);
}
}
------------------------
** 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:
-------
** 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:
---------------
** NavigableSet(I)
-------------------
>it is child interface of SortedSet.
** NavigableMap(I):
--------------------
> its child interface of SortedMap.
Method:
-------
1 floorKey(e) ; // return highest element which is <= e.
** UTILITY CLASSES:
-------------------
* Collections
* Arrays
* Collections(C):
--------------------------------------------------
> Collections class is an utility class , present in java.util package to define
Utility Methods for Collection Objects.
ex: Collections.sort(al);
ex:
Collections.sort(al);
System.out.println("BinarySearch :"+Collections.binarySearch(al, "C"));
**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.
2 reverseOrder();
** reverse() Vs reverseOrder():
==================================
1 reverse() :=> to reverse order of elements of list.
-----------------------------------------------------------------------------------
-----------
** ARRAYS:
-----------
>Arrays class is an Utility class to define several utility methods for Array
Objects.
*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);
Note: all rules of arrays class binarySearch() are exactally same as Collections
class binarySearch()
---------------------------
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.
-----------------------------------------------------------------------------------
-----
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.
1 ConcurrentHashMap
2 CopyOnWriteArrayList
3 ColyOnWriteArraySet
** ConcurrentMap(C):
--------------------
Map(I):
|
ConcurrentMap(I)
|
ConcurrentHashMap(C):
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.
-------------
*****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.
Note:- while one thread iterating , the other thread can perform update operation
and ConcurrentHashMap never threw ConcurrentModificationException
** CONSTRUCTORS:
===============
** 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.
5 null is allowed for both keys and values 5 null is not allowed for
both keys and values-get=>NPE
-----------------------------------------------------------------------------------
--------------------------------------
** 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
** 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.
** CONSTRUCTOR:
===============
** Method:
==========
1 boolean addIfAbsent(Object o);
--------------------------------
=> element will be added if List do not contains this element.
** 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
** DIFF BW:
CopyOnWriteArrayList SycronizedList()
vector()
-----------------------------------------------------------------------------------
-----------------------------------
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.
-----------------------------------------------------------------------------------
--------------------------------------
** 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:
---------------
** 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.
4 Iterator can perform only Read operation can not perform Remove operation.
4 Iterator can perform only Read operation can
not perform Remove operation.
-----------------------------------------------------------------------------------
-----------------------------------------
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.
-----------------------------------------------------------------------------------
----------------------------------------
** 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.
> 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:
---------------
** METHODS:- [does not containing any new mehtods , use general Map mehtods only]
-----------------------------------------------------------------------------------
---------------------------
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.
-----------------------------------------------------------------------------------
--------------------------------