Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 11

Collection

|
|
|
List | Set(I)
Queue(I)
| | | | |
| |
| | | HashSet |
| |
ArrayList LinkedList Vector | SortedSet
| |
| LinkedHashSet |
| |
Stack
NavigableMap(I) PriorityQueue BLOCKINGQUEUE
|
|

TreeSet |--PRIORITYBLOCKINGQUEUE

|--LINKEDBLOCKINGQUEUE

Q) Differece between ArrayList and LinkedList ?

ArrayList
LinkedList
1.It Internaly use dynamic array to store the elements
1.it uses internally a double LinkedList to store the elements.
2.Manupulation ArrayList is slow because it internally use and
2.Manupulation of LinkedList is faster than ArrayList
array.if any element removed from array,all bits are shifted
because it uses a doubly linked list, so no bit shifting
in memory.
is required in memory.

3.An ArrayList class can act as a list only because


3.LinkedList class can act as a list and queue both because it implements List and
Deque interfaces.
it implements List only.

4. ArrayList is better for storing and accessing data.


4.LinkedList is better for manipulating data

Q)ArrayList ?
1.The Underlying Data Structure is Double LinkedList.
2.Insertion Order is Preserved.
3.Duplicate Objects are allowed.
3.Heterogeneous Objects are allowed.
4.null Insertion is Possible.
5.Implements Serializable and Cloneable Interfaces but Not RandomAccess
Interface.
6.Best Choice if Our Frequent Operation is Insertion OR Deletion in the Middle.
7.Worst Choice if Our Frequent Operation is Retrieval.
LinkedList:
1.The Underlying Data Structure is Double LinkedList.
2.Insertion Order is Preserved.
3.Duplicate Objects are allowed.
4.Heterogeneous Objects are allowed.
5.null Insertion is Possible.
6.Implements Serializable and Cloneable Interfaces but Not
RandomAccessInterface.
7.Best Choice if Our Frequent Operation is InsertionOR Deletion in the Middle.
8.Worst Choice if Our Frequent Operation is Retrieval
Vector:
New Capacity = Current Capacity * 2
1.The Underlying Data Structure is Resizable Array OR Growable Array.
2.Insertion Order is Preserved.
3.Duplicate Objects are allowed.
4.Heterogeneous Objects are allowed.
5.null Insertion is Possible.
6.Implements Serializable, Cloneable and RandomAccess interfaces.
7.Every Method Present Inside Vector is Synchronized and Hence Vector Object is
Thread Safe.
8.Vector is the Best Choice if Our Frequent Operation is Retrieval.
9.Worst Choice if Our Frequent Operation is Insertion OR Deletion in the Middle.
Stack:
It is the Child Class of Vector.
It is a Specially Designed Class for Last In First Out (LIFO) Order.
1) Object push(Object o); To Insert an Object into the Stack.
2) Object pop(); To Remove and Return Top of the Stack.
3) Object peek(); Ro Return Top of the Stack without Removal.
4) boolean empty(); Returns true if Stack is Empty
5) int search(Object o);Returns Offset if the Element is Available Otherwise
Returns -1
Q)Detect Loop in LinkedList?
First, you keep two pointers of the head node.
At each iteration, you move one of the pointers by two steps and the other
one by one step. So you have two pointers tortoise and the hare.
Eventually one of the two cases will happen:
Hare will reach the tail of the linked list(null), which means that there is
no cycle in it
Hare will meet tortoise, which means that there is a cycle
Time complexity is O(N) where N is the number of nodes in the linked list,
space complexity is O(1) as you use only two pointers.

Q)Default capacity and load factor in collections?


Collection Initial-Capacity Load-Factor NewCapacity
ArrayList 10 0.75 New Capacity =
(Current Capacity * 3/2)+1
Vector 10 0.75 New Capacity =
Current Capacity * 2
HashSet 16 0.75
HashMap 16 0.75
Hashtable 11 0.75

Q)Difference between collections and array ?


Arrays Collection
------
----------
1.Arrays are Fixed in Size. ! 1.Collection are Growable in
Nature.
2.With Respect to memory arrays are not ! 2.With Respect to memory
Collections are
Recommanded to Use. ! Recommanded to Use.
3.With Respect to Performance arrays are ! 3.With Respect to Performance
Collections are not
Recommanded to Use. ! Recommanded to Use.
4.Arrays can Hold Homogeneous Data Elements ! 4.Collection can Hold Both
HOmogeneous and Hetrogeneous.
5.Arrays can Hold Both primitives and Objects ! 5.Collections can Hold only
objects but not primitives
6.Arrays concepts is Not implemented based on ! 6.For every Collections class
underlying Data Structure
some standard data structure.Hence Ready made ! is avilabl.Hence Readymade
method support is avilable
method support is Not avilable. ! for every requirement.

=====================================================================SET===========
=====================================================================
Set:
1.It is the Child Interface of Collection.
2.If we want to Represent a Group of Individual Objects as a Single Entity where
Duplicates are Not allowed and Insertion Order is Not Preserved then we should go
for Set.
3.Set Interface doesn't contain any New Methods and Hence we have to Use Only
Collection Interface Methods

Q)Hashset ?
The Underlying Data Structure is Hashtable.
1.Insertion Order is Not Preserved and it isBased on hashCode of the Objects.
2.Duplicate Objects are Not Allowed. If we are trying to Insert Duplicate
Objects then we
won't get any Compile Time ORRuntime Error.add() Simply Returns false.
3.null Insertion is Possible.
4.Heterogeneous objects are allowed.
5.HashSet implements Serializable and Cloneable Interfaces but Not
RandomAccess.
6.If Our Frequent Operation is Search Operation, then HashSet is the Best
Choice.
LinkedHashSet:
1.The Underlying Data Structure is a Combination of LinkedList and Hashtable
2.Insertion Order will be Preserved.
3.Introduced in 1.4 Version.

SortedSet:
1.It is the Child Interface of Set.
2.If we want to Represent a Group of Individual Objects without Duplicates and
all Objects will be Inserted According to Some Sorting Order,
then we should go for SortedSet.
3. The Sorting can be Either Default Natural Sorting OR Customized Sorting
Order.
4. For String Objects Default Natural Sorting is Alphabetical Order.
5. For Numbers Default Natural Sorting is Ascending Order.
Methods :
Object first(); Returns 1 st Element of the SortedSet.
Object last(); Returns Last Element of the SortedSet.
SortedSet headSet(Object obj); Returns SortedSet whose
Elements are < Object.
SortedSet tailSet(Object obj); Returns SortedSet whose Elements
are >= Object
SortedSetsubSet(Object obj1, Object obj2); Returns SortedSet
whose Elements are >= obj1 and <obj2
Comparator comparator(); Returns Comparator Object that
Describes Underlying SortingTechnique.
If we
are using Default Natural Sorting Order then we will get null.

TreeSet:
1. The Underlying Data Structure is Balanced Tree.
2. Insertion Order is Not Preserved and it is Based on Some Sorting Order.
3. Heterogeneous Objects are Not Allowed. If we are trying to Insert we will
get Runtime Exception Saying ClassCastException.
4. Duplicate Objects are Not allowed.
5. null Insertion is Possible (Only Once).--re check
6. Implements Serializable and Cloneable Interfaces but Not RandomAccess
Interface
=====================================================================MAP===========
==========================================================================
Map(i)
|
|
|
|
| | | | |
Disctionary(AC)
| | | |
|
| | | |
HashTabe
| | | | |
|
| | | |
|
HashMap WeakHashMap IdentityHashMap SortedMap
Properties
| |
|
|
LinkedHashMap NavigableMap
|

TreeMap

Map methods:
-----------
Object put(Object key, Object value);
putAll(Map m) , get(Object key),remove(Object key) ,containsKey(Object
key),containsValue(Object
value),isEmpty() ,size(),clear(),keySet(),values(),entrySet()

HashMap:
-------
1.The Underlying Data Structure is Hashtable.
2.Duplicate Keys are Not Allowed. But Values can be Duplicated.
3.Heterogeneous Objects are allowed for Both Keys and Values.
4.Insertion Order is not preserved and it is based on hash code of the keys
5.null Insertion is allowed for Key (Only Once) and allowed for Values (Any Number
of Times)

Q) Differece between HashTable and HashMap?

HashMap
Hashtable
-------
---------
1.No Method Present in HashMap is Synchronized 1.Every Method Present in
Hashtable is Synchronized.
2.At a Time Multiple Threads are allowed to 2.At a Time Only One
Thread is allowed to Operate on the Hashtable Object and
Operate on HashMap Object Hence it is Thread Safe.
simultaneously and Hence it is Not Thread
Safe
3.Relatively Performance is High. 3.Relatively Performance
is Low
4.null is allowed for Both Keys and Values. 4.null is Not allowed for
Both Keys and Values. Otherwise we will get NPE.
5.Introduced in 1.2 Version and it is Non–Legacy. 5.Introduced in 1.0
Version and it is Legacy.

Q)Differencesbetween HashMap vs LinkedHashMap ?


HashMap LinkedHashMap
----------------- --------------
1.The Underlying Data Structure is Hashtable. 1.The Underlying Data
Structure is Combination of Hashtable and LinkedList.
2.Insertion is Not Preserved. 2.Insertion Order is
Preserved.
3.Introduced in 1.2 Version. 3.Introduced in 1.4
Version.
Q)what is Identity HashMap?
1.It is Exactly Same as HashMap Except the following Difference.
2.In HashMap JVM will Use .equals() to Identify Duplicate Keys, which is Meant
for ContentComparision.
3.In IdentityHashMap JVM will Use == Operator to Identify Duplicate Keys, which
is Meant for Reference Comparison.
Q)what is WeakHashMap?
1. It is Exactly Same as HashMap Except the following Difference.
2. In Case of HashMap, HashMap Dominates Garbage Collector. That is if Object
doesn’t have any Reference Still it is Not Eligible for
Garbage Collector if it is associated with HashMap.
3. But In Case of WeakHashMap if an Object doesn't contain any References then
it is Always Eligible for GC Even though it is associated with
WeakHashMap. That is Garbage Collector Dominates WeakHashMap.
Q)what is SortedMap?
1.It is the Child Interface of Map.
2.If we want to Represent a Group of Key - Value Pairs According Some Sorting
Order of
3.Keys then we should go for SortedMap.
Object firstKey(); Object lastKey(); SortedMapheadMap(Object key)
SortedMaptailMap(Object key)
SortedMapsubMap(Object key1, Object key2) Comparator comparator()
Q)What is TreeMap?
1. The Underlying Data Structure is Red -Black Tree.
2.Duplicate Keys are Not Allowed. But Values can be Duplicated.
3.Insertion Order is Not Preserved and it is Based on Some Sorting Order of
Keys.
4.If we are depending on Default Natural Sorting Order then the Keys should be
Homogeneous and Comparable. Otherwise we will get
Runtime Exception Saying ClassCastException.
5.If we defining Our Own Sorting by Comparator then Keys can be Heterogeneous
and NonComparable.
But there are No Restrictions on Values. They can be Heterogeneous and Non-
Comparable.

Q)what is Hashtable?
Creates an Empty Hashtable Object with Default Initial Capacity 11 and Default
Fill Ratio 0.75.
1.The Underlying Data Structure for Hashtable is Hashtable Only.
2.Duplicate Keys are Not Allowed. But Values can be Duplicated.
3.Insertion Order is Not Preserved and it is Based on Hashcode of the Keys.
4.Heterogeneous Objects are Allowed for Both Keys and Values.
5.null Insertion is Not Possible for Both Key and Values. Otherwise we will
get Runtime Exception Saying NullPointerException.
6.Every Method Present in Hashtable is Synchronized and Hence Hashtable Object
is Thread Safe.

Q)Properties:
1.It is the Child Class of Hashtable.
2.In Our Program if anything which Changes Frequently
3.The Main Advantage in this Approach is if a there is a Change in
Properties File, to Reflect that Change Just Redeployment is Enough,
which won't Create any Business Impact.
4.We can Use Properties Object to Hold Properties which are coming from
Properties File.
5. Properties can be used to Represent a Group of Key – Value Pairs where Both
Key and Value should be String Type.

========================================================================QUEUE======
=================================================================

QUEUE

| | | |
| | |
| |
|
| | |
|
| |
|
| |
|
PRIORIRTYQUEUE
TRANSFERQUEUE BLOCKINGQUEUE

|---- PRIORITYQUEUE

|-----
LINKEDBLOCKINGQUEUE
Queue:
1. Queue is a Child Interface of Collection.
2.If we want to Represent a Group of Individual Objects Prior to processing then we
should go for Queue.
3.From 1.5 Version onwards LinkedList also implements Queue Interface.
4. Usually Queue follows FIFO Order. But Based on Our Requirement we can Implement
Our Own Priorities Also (PriorityQueue).
5. LinkedList based Implementation of Queue always follows FIFO Order.
boolean offer(Object o); -- To Add an Object into the Queue.
Object peek(); --To Return Head Element of the Queue ,If Queue is Empty
then this Method Returns null.
Object element(); --To Return Head Element of the Queue,If Queue is Empty then
this Methodraises RE: NoSuchElementException
Object poll(); --To Remove and Return Head Element of the Queue,If Queue is
Empty then this Method Returns null
Object remove(); --To Remove and Return Head Element of the Queue,If Queue
is Empty then this Method raise RE: NoSuchElementException.

PriorityQueue:
1.This is a Data Structure which can be used to Represent a Group of Individual
Objects
2.Prior to processing according to Some Priority.
3.The Priority Order can be Either Default Natural Sorting Order OR Customized
Sorting Order specified by Comparator Object.
4.If we are Depending on Natural Sorting Order then the Objects should be
Homogeneous and Comparable otherwise we will get ClassCastException.
5.If we are defining Our Own Sorting by Comparator then the Objects Need Not
beHomogeneous and Comparable.
6.Duplicate objects are Not Allowed.
7.Insertion Order is Not Preserved and it is Based on Some Priority.
8. null Insertion is Not Possible Even as 1st Element Also.

BlockingQueue:
1.It is the Child Interface of Queue. Present in java.util.Concurrent Package.
2. It is a Thread Safe Collection.
3.It is a specially designed Collection Not Only to Store Elements but also
Supports Flow Control by Blocking Mechanism.
4.If Queue is Empty take() (Retrieval Operation) will be Blocked until Queue will
be Updated with Items.
5. put() will be blocked if Queue is Full until Space Availability.
6.This Property Makes BlockingQueue Best Choice for Producer Consumer Problem.
When One Thread producing Items to the Queue and
the Other Thread consuming Items from the Queue.

TransferQueue:
1.In BlockingQueue we can Only Put Elements into the Queue and if Queue is Full
then Our put() will be blocked until Space is Available.
2.But in TransferQueue we can also Block until Other Thread receiving Our
Element. Hence this is the Behavior of transfer().
3.In BlockingQueue we are Not required to wait until Other Threads Receive Our
Element but in TransferQueue we have to wait until Some Other
Thread Receive Our Element.
4.TrasferQueue is the Best Choice for Message Passing Application where
Guarantee for the Delivery.

Collections (C):
---------------
Collections Class is an Utility Class Present in java.util Package to Define
Several Utility Methods for Collection Objects.

public static void sort(List l);


public static void sort(List l, Comparator c);
public static intbinarySearch(List l, Object target);
public static intbinarySearch(List l, Object target, Comparator c);

======================================================Concurrent
Collections=======================================================================

Q)Difference between HashMap and ConcurrentHashMap ?


HashMap
ConcurrentHashMap
------------
-------------------
1. It is Not Thread Safe. ! 1. It is
Thread Safe.
2. Relatively Performance is High because ! 2. Relatively
Performance is Low because Some
Threads are Not required to wait to Operate ! Times
Threads are required to wait to Operate
on HashMap. ! on
ConcurrentHashMap.
3. While One Thread iterating HashMap the ! 3. While One
Thread iterating
Other Threads are Not allowed to Modify Map !
ConcurrentHashMap the Other Threads are
Objects Otherwise we will get Runtime ! allowed to
Modify Map Objects in Safe
Exception Saying ! Manner and
it won’t throw
ConcurrentModificationException. !
ConcurrentModificationException.
4. Iterator of HashMap is Fail-Fast and it throws ! 4. Iterator
of ConcurrentHashMap is Fail-Safe
ConcurrentModificationException. ! and it
won’t
5. null is allowed for Both Keys and Values. ! 5. null is
Not allowed for Both Keys and Values.
6. Introduced in 1.2 Version. ! 6. Introduced
in 1.5 Version.

Q) Difference between ConcurrentHashMap, synchronizedMap() and Hashtable ?

--------------------- -------------------
-------------
ConcurrentHashMap synchronizedMap()
Hashtable
-------------------- -------------------
------------

1. We will get Thread Safety ! 1. We will get Thread Safety by


! 1. We will get Thread Safety by
without locking Total Map ! locking Whole Map Object.
! locking Whole Map Object.
Object Just with Bucket Level !
!
Lock. !
!
2. At a Time Multiple Threads ! 2. At a Time Only One Thread is
! 2. At a Time Only One Thread is
are allowed to Operate on ! allowed to Perform any
! allowed to Operate on Map
Map Object in Safe Manner. ! Operation on Map Object.
! Object.
3. Read Operation can be ! 3. Every Read and Write
! 3. Every Read and Write
performed without Lock but ! Operations require Total Map
! Operations require Total Map
write Operation can be ! Object Lock.
! Object Lock.
performed with Bucket Level !
!
Lock. !
!
4. While One Thread iterating ! 4. While one thread iterating
! 4. While One Thread iterating
Map Object, the Other ! Map Object, the Other
! Map Object, the Other
Threads are allowed to ! Threads are Not allowed to
! Threads are Not allowed to
Modify Map and we won’t get ! Modify Map. Otherwise we get
! Modify Map. Otherwise we will
ConcurrentModificationException. ! get
ConcurrentModificationException. ! get ConcurrentModificationException.
5. Iterator of ConcurrentHashMap ! 5. Iterator of synchronizedMap
! 5. Iterator of synchronizedMap
is FailSafe and won’t raise ! is Fail-Fast and it will raise
! is Fail-Fast and it will raise
ConcurrentModificationException. ! ConcurrentModificationException.
! ConcurrentModificationException.
6. null is Not allowed for Both ! 6. null is allowed for Both Keys
! 6. null is allowed for Both Keys
Keys and Values. ! and values.
! and values.
7. Introduced in 1.5 Version. ! 7. Introduced in 1.2 Version.
! 7. Introduced in 1.0 Version.

Q) HashMap internal architecture ?


1.The default size of HashMap is 16 (0 to 15).
2.PUT : Then it calculates the hash code of the Key , To store the Key in
memory, we have to calculate the index.
Index = hashcode(Key) % (n-1)
3. calculated index value is the same for two or more Keys
4.If Keys are same, replace the value with the current value else connect
this node object to the existing node object through the LinkedList.
5.every node maintains hashcode,key,value,next node address
6.get : it calculates the hash code of the Key ,with hashcode calculate the
index value of hashcode.
7.get() method search for the index value 4. It compares the first element
Key with the given Key.
8.If both keys are equal, then it returns tphe value else check for the next
element in the node if it exists.
8.If both keys are equal, then it returns the value else check for the next
element in the node if it exists.
Q)Internal architecture of HashSet ?

Q)Comparison Table of 3 Cursors ?

--------------------- ----------------------------
----------------------------------- --------------------------
Property Enumeration
Iterator ListIterator
--------------------- -----------------------------
------------------------------------ ---------------------------

1) Applicable For ! 1) Only Legacy Classes ! 1) Any


Collection Object ! 1) Only List Object
2) Movement ! 2) Single Direction(Only Forward) ! 2) Single
Direction(Only Forward) ! 2) Bi-Direction
3)How To Get ! 3) By using elements() ! 3) By using
iterator() ! 3) By using listIterator() of List(I)
4) Accessability ! 4) Only Read ! 4) Read and
Remove ! 4) Remove, Replace And Addition of New Objects
5) Methods ! 5) hasMoreElements() ! 5)
hasNext() ! 5) 9 Methods (hasNext(),nex(),nextIndex(),
! nextElement() ! next() ,
remove() ! (hasPrevious(),previous(),previosIndex()
!
! !
remove(),set(),add()
6) Is it legacy? ! 6) Yes (1.0 Version) ! 6) No (1.2
Version) ! 6) No (1.2 Version)

Q)Difference between HashSet and HashMap class in Java?

-----------------------------------------------------------------------------------
---------------------------------------------------------
HashMap |
HashSet
|
-----------------------------------------------------------------------------------
---------------------------------------------------------

|
1) In HashMap we store a key-value pair. It maintains the mapping of | 1.In
HashSet, we store objects
key and value
|
2)It does not allow duplicate keys, but duplicate values are allowed. | 2.It
does not allow duplicate values.
3)It can contain a single null key and multiple null values |
3.It can contain a single null value.
5)HashMap uses the put() method to add the elements in the HashMap. |
5.HashSet uses the add() method to add elements in the HashSet.

|
6)HashMap is faster/ than HashSet because values are associated with |
6)HashSet is slower than HashMap because the member object is
a unique key.
| used for calculating hashcode can same for two objects.
7)Only one object is created during the add operation.
| 7)There are two objects created during put operation,

| one for key and one for value


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

You might also like