Java Collection
By Deepak Kumar
About me..
▪ Deepak Kumar
▪ Code for this learning: https://github.com/mcapatna/core_Java/
▪ Slides for this learning : https://www.slideshare.net/mcapatna/
▪ Questions you may ask during session after session or whenever you
find me free otherwise you may ask on SO.
https://stackoverflow.com/users/1771440/the-powerhouse
▪ Missed some concept recall it on https://javadoc4.wordpress.com/
index
▪ Array Introduction
▪ Navigation technique intro
▪ A bit on synchronized
▪ Collection Hierarchy
▪ CollectionVs Collections
▪ List interface
▪ Queue interface
▪ Set Interface.
▪ Map Interface
Array
▪ Advantage:
– Can store multiple value in a single variable.
– Faster & Easier to access any element using index .
– More readable
▪ Issues
– Fixed size
– Insertion/deletion in the middle is complex.
– Continuous memory location.
– Homogeneous object
– programmer has to write complex logic
▪ Sun has provided few classes and interfaces since its birth mainlyVector, stack,
hashtables, properties , dictionary, Enumeration.
▪ Some other collection libraries are guava, FastUtil, Eclipse collections, JcTools
index
▪ Array Introduction
▪ Navigation technique intro
▪ A bit on synchronized
▪ Collection Hierarchy
▪ CollectionVs Collections
▪ List interface
▪ Queue interface
▪ Set Interface.
▪ Map Interface
Navigation through collection
▪ Iterator
▪ ListIterator
▪ Enumaration
▪ SplitIterator
▪ Others
▪ Fail-Fast & Fail-Safe type
Enumeration
▪ Legacy interface.The functionality of this interface is duplicated by
the Iterator interface.
▪ Remove method is not present.
▪ Long names
▪ Iterator Enumeration
hasNext() hasMoreElements()
next() nextElement()
remove() not present
▪ Normally it is used to iterate the legacy classes like vector hashtable
etc
Iterator
▪ Iterator adds an optional remove operation, and has shorter method names of
Enumeration.
▪ Access the element in forward direction using hasNext & next .
▪ Sequential access and one element at a time
▪ Index of element is not provided by iterator
▪ Can traverse set ,list or Map.
▪ You can’t add or set any element using iterator.
▪ New implementations should consider using Iterator in preference to Enumeration.
ListIterator
▪ Traverse in both Direction
▪ Can be use only with List but not with set or map
▪ Add and set method are provided with ListIterator
▪ You can get the current position
▪ nextIndex() , previousIndex() gives us the indexes
Fail-fast and Fail-safe
Changing the structure after iterator creation except iterator own remove() method will throw
CME in case of fail-fast iterator .
java.lang.IllegalStateException java.util.ConcurrentModificationException
index
▪ Array Introduction
▪ Navigation technique intro
▪ A bit on synchronized
▪ Collection Hierarchy
▪ CollectionVs Collections
▪ List interface
▪ Queue interface
▪ Set Interface.
▪ Map interface
Tollgate example for synchronized
index
▪ Array Introduction
▪ Navigation technique intro
▪ A bit on synchronized
▪ Collection Hierarchy
▪ CollectionVs Collections
▪ List interface
▪ Queue interface
▪ Set Interface.
▪ Map interface
index
▪ Array Introduction
▪ Navigation technique intro
▪ A bit on synchronized
▪ Collection Hierarchy
▪ CollectionVs Collections
▪ List interface
▪ Queue interface
▪ Set Interface.
▪ Comparable & comparator
Interfaces : Iteratable , collection
Classes: Collections, Arrays
▪ Functional interface Iteratable :contains 3 methods iterator, forEach &
spliterator .
▪ Collection :the root of collection hierarchy which contains method contract for
basic operation like add ,remove size, isEmpty etc
▪ Collections and Arrays classes contains multiple utility methods.
▪ Collection ,List, Set,SortedSet,NavigableSet,Queue,Map,SortedMap &
NavigableMap are some key interfaces used to store group of object.
▪ Normally every collection class implements serializable.
▪ Serialver command is used to see the serial version of the class
index
▪ Array Introduction
▪ Navigation technique intro
▪ A bit on synchronized
▪ Collection Hierarchy
▪ CollectionVs Collections
▪ List interface
▪ Queue interface
▪ Set Interface.
▪ Comparable & comparator
List Interface
▪ Ordered collection/sequence
▪ Allows duplicates
▪ Allows null
▪ Insertion order preserve
▪ Implementing Classes ArrayList, CopyOnWriteArrayList, LinkedList,
Stack,Vector
List interface
▪ Vector
▪ ArrayList
▪ LinkedList
▪ CopyOnWriteArrayList
Output
ArrayList
▪ public class ArrayList<E> extends AbstractList<E> implements
List<E>, RandomAccess, Cloneable, Serializable
▪ Resizable-array implementation of the List interface.
▪ Permits null
▪ Insertion time O(n) .other operation has O(1)
▪ Non synchronized. List list = Collections.synchronizedList(new LinkedList(...));
▪ The iterators returned by this class's iterator and listIterator methods are fail-fast.
▪ Three constructors.
▪ Default initial capacity is 10.
▪ In case of retrieval ArrayList is a good selection whereas if you have to
insert/deletion in the middle it is not a good selection.
vector
▪ Synchronized
▪ Legacy class
▪ public classVector<E> extends AbstractList<E> implements List<E>,
RandomAccess, Cloneable, Serializable
▪ Stack is direct subclass of vector
▪ The iterators returned by this class's iterator , listIterator & spliterator
methods are fail-fast.
▪ The Enumerations returned by the elements method are fail-safe
▪ Default constructor create the vector of size 10.
▪ 4 constructors.
LinkedList
▪ public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>,
Deque<E>, Cloneable, Serializable
▪ Doubly-linked list implementation of the List and Deque interfaces.
▪ Permits null
▪ Non synchronized. List list = Collections.synchronizedList(new LinkedList(...));
▪ The iterators returned by this class's iterator and listIterator methods are fail-fast.
▪ Insertion & deletion from middle is easy. Retrieval is costly
▪ 2 constructors.
CopyOnWriteArrayList
▪ java.util.concurrent
▪ public class CopyOnWriteArrayList<E> extends Object implements List<E>,
RandomAccess, Cloneable, Serializable
▪ A thread-safe variant of ArrayList in which all mutative operations (add, set, and so on)
are implemented by making a fresh copy of the underlying array.
▪ No need to lock or copy the collection during iteration.
▪ The iterators do not throw ConcurrentModificationException and return exactly as they
were at the time the iterator was created, regardless of subsequent modifications.
▪ As long as a object is not changeable there is no need of synchronization.
▪ Costly
Collection contd..
Waiting for question/suggestion from previous session
index
▪ Array Introduction
▪ Navigation technique intro
▪ A bit on synchronized
▪ Collection Hierarchy
▪ CollectionVs Collections
▪ List interface
▪ Queue interface
▪ Set Interface.
▪ Map Interface
Queue interface
▪ A collection which stores the element prior to processing [no need to process immediatly ] examples CPU
Scheduling ,Disk scheduling, Asynchronous Data transfer etc
▪ Provides additional insertion, extraction, and inspection operations along with collection method in two
format.
▪ Normally (not always) it follow in FIFO order.
▪ Few Sub interfaces: BlockingDeque<E>, BlockingQueue<E>, Deque<E>,TransferQueue<E>
▪ The important classes are: ArrayBlockingQueue, ArrayDeque, ConcurrentLinkedDeque,
ConcurrentLinkedQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, LinkedList,
LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue, SynchronousQueue
Throws exception Returns special value [null /false ]
Insert add(e) offer(e)
Remove remove() poll()
Examine element() peek()
Queue contd….
Enqueue dequeuer
TAIL/Rear Head/Front
 Insertion is from tail deletion is from head deletion is from rear.
 add() will add the element at the tail of queue or according to the priority wise
 peek() get the first element from the queue without deleting it null if queue is empty
 element() same as peek() but throws a NoSuchElementException if queue is empty
 remove() get the head of the queue and delete it. NoSuchElementException if queue is empty
 poll() same as remove except return a null if queue is empty
 Other methods inherited from collection
PriorityQueue
▪ Does not allow null
▪ The element of the priority queue must be comparable. Insertion of Two non comparable
class will result classCastException.
▪ Initial capacity is 11
▪ Non synchronized
Blocking Queue Interface
▪ A Queue that additionally supports operations that wait for the queue to become non-
empty when retrieving an element, and wait for space to become available in the
queue when storing an element.
▪ Null is not allow at the time of insertion
▪ few implementation classes are ArrayBlockingQueue, DelayQueue,
LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue
▪ Try to create a solution for consumer-producer problem
Throws exception Special value Blocks Times out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicable not applicable
Interface Deque
▪ Double ended queue which can support insertion and deletion from both end.
▪ Implementation classes ArrayDeque, ConcurrentLinkedDeque, LinkedBlockingDeque,
LinkedList
▪ Application using Deque can be A-steal Job Scheduling,undo task etc
index
▪ Array Introduction
▪ Navigation technique intro
▪ A bit on synchronized
▪ Collection Hierarchy
▪ CollectionVs Collections
▪ List interface
▪ Queue interface
▪ Set Interface.
▪ Map Interface
Set interface
▪ Duplicate elements wont be allowed.
▪ The duplicity is defined on the implementation of equals()
▪ There is a contract with equals() & hashCode()
▪ Insertion order are normally not preserve.
▪ ListIterator can’t be used to iterate a set
▪ Allowing null depends on implementation classes
▪ NavigableSet,SortedSet are sub interfaces
▪ Important classes are HashSet , LinkedHashSet ,TreeSet,
CopyOnWriteArraySet, EnumSet
▪ Guava’s multiset implementation allow duplicate elements
Hashset
▪ Internally hashtable data structure
▪ Allow Null
▪ Insertion order does not preserve
▪ Non synchronized Set s = Collections.synchronizedSet(new
HashSet(...));
▪ Iterator return by this class iterator methods are fail-fast
▪ Default Initial capacity =16 load factor =0.75
Removing duplicates from List
Output
TreeSet
▪ Treeset implements navigableSset & sortedset. It internally uses treemap.
▪ Element stored in the treeset are sorted in natural order.
▪ Any custom defined class should be a type of comparable because internally
compareTo() is used to decide the order.
▪ You will get NPE if you try to store any null Object.
▪ Non synchronized
▪ Iterators are fail-fast
▪ classCastExpcetion
▪ Slower than hashset
index
▪ Array Introduction
▪ Navigation technique intro
▪ A bit on synchronized
▪ Collection Hierarchy
▪ CollectionVs Collections
▪ List interface
▪ Queue interface
▪ Set Interface
▪ Map Interface
Map interface
▪ Stores the elements in Key-Value pair / Entry.
▪ Key can’t be duplicate but the values can.
▪ Storing the different value for exiting key will override the previous and returns old key
▪ Not a part of collection framework but provides 3 different collection views to get list of key object
,list of values object and list of entry
▪ Different methods available in this interface are put ,get, remove ,containsKey ,containsValue,
keyset, values, entrySet ,putIfAbsent,compute ,clear etc.
▪ A map can’t contains itself to a key but it can be a value of itself.
▪ Implementation classes includes Hashtable, HashMap, ConcurrentHashMap,
ConcurrentSkipListMap, IdentityHashMap, LinkedHashMap, Properties, RenderingHints,TreeMap,
WeakHashMap etc
Hashtable
▪ This class implements a hash table, which maps keys to values. Any
non-null object can be used as a key or as a value.
▪ initial capacity and load factor
▪ hash collision
▪ It is synchronized .performance is lower than HashMap.
▪ Null is not allowed for both key & value
▪ Iterating over hashtable
for(Map.Entry m:hm.entrySet()) {System.out.println(m.getKey()
+" "+m.getValue()); }
HashMap
▪ public class HashMap<K,V> extends AbstractMap<K,V> implements
Map<K,V>, Cloneable, Serializable{….}
▪ Underlying data structure hashtable
▪ No insertion order
▪ Single Null as key is allowed
▪ Default initial capacity 16 & load factor 0.75
▪ Non synchronized .
▪ Collections.synchronizedMap(hm_from_map);
LinkedHashMap
▪ public class LinkedHashMap<K,V> extends HashMap<K,V>
implements Map<K,V>
▪ Underlying datastructure linked list and hashtable.
▪ Unlike hashMap Insertion order preserved
▪ Permits nulls. more than one null as a key will be overridden & there
is no effect on insertion order.
▪ Non Synchronized
▪ Iterators are fail-fast.
WeakHashMap
▪ Hastable based implementation with weak keys.
▪ The entry in weakhashmap will automatically removed if its key is no longer in
use
▪ Both null key and null values are supported
▪ Non synchronized
▪ Iterators are fail-fast
▪ Default initial capacity is 16 and default load factor is 0.75
▪ Depending on the current key is garbage collected or not the different methods
like size(),IsEmpty() etcof this map implementation may behave differently
Title and Content Layout with Chart
Principal collection class Base class Base interfaces Allow duplicate
elements?
Ordered? Sorted? Thread-safe?
ArrayList<E> AbstractList<E> List<E> Yes Yes No No
LinkedList<E> AbstractSequentialList<E> List<E>;
Deque<E>
Yes Yes No No
Vector<E> AbstractList<E> List<E> Yes Yes No Yes
HashSet<E> AbstractSet<E> Set<E> No No No No
LinkedHashSet<E> HashSet<E> Set<E> No Yes No No
TreeSet<E> AbstractSet<E> Set<E>;
NavigableSet<E>;
SortedSet<E>
No Yes Yes No
HashMap<K, V> AbstractMap<K, V> Map<K, V> No No No No
LinkedHashMap<K, V> HashMap<K, V> Map<K, V> No Yes No No
Hashtable<K, V> Dictionary<K, V> Map<K, V> No No No Yes
TreeMap<K, V> AbstractMap<K, V> Map<K, V>;
NavigableMap<K, V>;
SortedMap<K, V>
No Yes Yes No
Question Hour …… ?
Refrances…
Oracle Doc : https://docs.oracle.com/javase/8/docs/api/
Stackoverflow https://stackoverflow.com/
Dzone https://dzone.com/articles/
Geesforgeek https://www.geeksforgeeks.org
Tutorialspoint http://www.tutorialspoint.com/
JavaPoint : https://www.javatpoint.com
Thanks

Java collection

  • 1.
  • 2.
    About me.. ▪ DeepakKumar ▪ Code for this learning: https://github.com/mcapatna/core_Java/ ▪ Slides for this learning : https://www.slideshare.net/mcapatna/ ▪ Questions you may ask during session after session or whenever you find me free otherwise you may ask on SO. https://stackoverflow.com/users/1771440/the-powerhouse ▪ Missed some concept recall it on https://javadoc4.wordpress.com/
  • 3.
    index ▪ Array Introduction ▪Navigation technique intro ▪ A bit on synchronized ▪ Collection Hierarchy ▪ CollectionVs Collections ▪ List interface ▪ Queue interface ▪ Set Interface. ▪ Map Interface
  • 4.
    Array ▪ Advantage: – Canstore multiple value in a single variable. – Faster & Easier to access any element using index . – More readable ▪ Issues – Fixed size – Insertion/deletion in the middle is complex. – Continuous memory location. – Homogeneous object – programmer has to write complex logic ▪ Sun has provided few classes and interfaces since its birth mainlyVector, stack, hashtables, properties , dictionary, Enumeration. ▪ Some other collection libraries are guava, FastUtil, Eclipse collections, JcTools
  • 7.
    index ▪ Array Introduction ▪Navigation technique intro ▪ A bit on synchronized ▪ Collection Hierarchy ▪ CollectionVs Collections ▪ List interface ▪ Queue interface ▪ Set Interface. ▪ Map Interface
  • 8.
    Navigation through collection ▪Iterator ▪ ListIterator ▪ Enumaration ▪ SplitIterator ▪ Others ▪ Fail-Fast & Fail-Safe type
  • 9.
    Enumeration ▪ Legacy interface.Thefunctionality of this interface is duplicated by the Iterator interface. ▪ Remove method is not present. ▪ Long names ▪ Iterator Enumeration hasNext() hasMoreElements() next() nextElement() remove() not present ▪ Normally it is used to iterate the legacy classes like vector hashtable etc
  • 11.
    Iterator ▪ Iterator addsan optional remove operation, and has shorter method names of Enumeration. ▪ Access the element in forward direction using hasNext & next . ▪ Sequential access and one element at a time ▪ Index of element is not provided by iterator ▪ Can traverse set ,list or Map. ▪ You can’t add or set any element using iterator. ▪ New implementations should consider using Iterator in preference to Enumeration.
  • 12.
    ListIterator ▪ Traverse inboth Direction ▪ Can be use only with List but not with set or map ▪ Add and set method are provided with ListIterator ▪ You can get the current position ▪ nextIndex() , previousIndex() gives us the indexes
  • 13.
    Fail-fast and Fail-safe Changingthe structure after iterator creation except iterator own remove() method will throw CME in case of fail-fast iterator . java.lang.IllegalStateException java.util.ConcurrentModificationException
  • 14.
    index ▪ Array Introduction ▪Navigation technique intro ▪ A bit on synchronized ▪ Collection Hierarchy ▪ CollectionVs Collections ▪ List interface ▪ Queue interface ▪ Set Interface. ▪ Map interface
  • 15.
  • 16.
    index ▪ Array Introduction ▪Navigation technique intro ▪ A bit on synchronized ▪ Collection Hierarchy ▪ CollectionVs Collections ▪ List interface ▪ Queue interface ▪ Set Interface. ▪ Map interface
  • 18.
    index ▪ Array Introduction ▪Navigation technique intro ▪ A bit on synchronized ▪ Collection Hierarchy ▪ CollectionVs Collections ▪ List interface ▪ Queue interface ▪ Set Interface. ▪ Comparable & comparator
  • 19.
    Interfaces : Iteratable, collection Classes: Collections, Arrays ▪ Functional interface Iteratable :contains 3 methods iterator, forEach & spliterator . ▪ Collection :the root of collection hierarchy which contains method contract for basic operation like add ,remove size, isEmpty etc ▪ Collections and Arrays classes contains multiple utility methods. ▪ Collection ,List, Set,SortedSet,NavigableSet,Queue,Map,SortedMap & NavigableMap are some key interfaces used to store group of object. ▪ Normally every collection class implements serializable. ▪ Serialver command is used to see the serial version of the class
  • 20.
    index ▪ Array Introduction ▪Navigation technique intro ▪ A bit on synchronized ▪ Collection Hierarchy ▪ CollectionVs Collections ▪ List interface ▪ Queue interface ▪ Set Interface. ▪ Comparable & comparator
  • 21.
    List Interface ▪ Orderedcollection/sequence ▪ Allows duplicates ▪ Allows null ▪ Insertion order preserve ▪ Implementing Classes ArrayList, CopyOnWriteArrayList, LinkedList, Stack,Vector
  • 22.
    List interface ▪ Vector ▪ArrayList ▪ LinkedList ▪ CopyOnWriteArrayList
  • 24.
  • 25.
    ArrayList ▪ public classArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable ▪ Resizable-array implementation of the List interface. ▪ Permits null ▪ Insertion time O(n) .other operation has O(1) ▪ Non synchronized. List list = Collections.synchronizedList(new LinkedList(...)); ▪ The iterators returned by this class's iterator and listIterator methods are fail-fast. ▪ Three constructors. ▪ Default initial capacity is 10. ▪ In case of retrieval ArrayList is a good selection whereas if you have to insert/deletion in the middle it is not a good selection.
  • 28.
    vector ▪ Synchronized ▪ Legacyclass ▪ public classVector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable ▪ Stack is direct subclass of vector ▪ The iterators returned by this class's iterator , listIterator & spliterator methods are fail-fast. ▪ The Enumerations returned by the elements method are fail-safe ▪ Default constructor create the vector of size 10. ▪ 4 constructors.
  • 31.
    LinkedList ▪ public classLinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable ▪ Doubly-linked list implementation of the List and Deque interfaces. ▪ Permits null ▪ Non synchronized. List list = Collections.synchronizedList(new LinkedList(...)); ▪ The iterators returned by this class's iterator and listIterator methods are fail-fast. ▪ Insertion & deletion from middle is easy. Retrieval is costly ▪ 2 constructors.
  • 32.
    CopyOnWriteArrayList ▪ java.util.concurrent ▪ publicclass CopyOnWriteArrayList<E> extends Object implements List<E>, RandomAccess, Cloneable, Serializable ▪ A thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array. ▪ No need to lock or copy the collection during iteration. ▪ The iterators do not throw ConcurrentModificationException and return exactly as they were at the time the iterator was created, regardless of subsequent modifications. ▪ As long as a object is not changeable there is no need of synchronization. ▪ Costly
  • 33.
    Collection contd.. Waiting forquestion/suggestion from previous session
  • 34.
    index ▪ Array Introduction ▪Navigation technique intro ▪ A bit on synchronized ▪ Collection Hierarchy ▪ CollectionVs Collections ▪ List interface ▪ Queue interface ▪ Set Interface. ▪ Map Interface
  • 35.
    Queue interface ▪ Acollection which stores the element prior to processing [no need to process immediatly ] examples CPU Scheduling ,Disk scheduling, Asynchronous Data transfer etc ▪ Provides additional insertion, extraction, and inspection operations along with collection method in two format. ▪ Normally (not always) it follow in FIFO order. ▪ Few Sub interfaces: BlockingDeque<E>, BlockingQueue<E>, Deque<E>,TransferQueue<E> ▪ The important classes are: ArrayBlockingQueue, ArrayDeque, ConcurrentLinkedDeque, ConcurrentLinkedQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, LinkedList, LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue, SynchronousQueue Throws exception Returns special value [null /false ] Insert add(e) offer(e) Remove remove() poll() Examine element() peek()
  • 36.
    Queue contd…. Enqueue dequeuer TAIL/RearHead/Front  Insertion is from tail deletion is from head deletion is from rear.  add() will add the element at the tail of queue or according to the priority wise  peek() get the first element from the queue without deleting it null if queue is empty  element() same as peek() but throws a NoSuchElementException if queue is empty  remove() get the head of the queue and delete it. NoSuchElementException if queue is empty  poll() same as remove except return a null if queue is empty  Other methods inherited from collection
  • 39.
    PriorityQueue ▪ Does notallow null ▪ The element of the priority queue must be comparable. Insertion of Two non comparable class will result classCastException. ▪ Initial capacity is 11 ▪ Non synchronized
  • 41.
    Blocking Queue Interface ▪A Queue that additionally supports operations that wait for the queue to become non- empty when retrieving an element, and wait for space to become available in the queue when storing an element. ▪ Null is not allow at the time of insertion ▪ few implementation classes are ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue ▪ Try to create a solution for consumer-producer problem Throws exception Special value Blocks Times out Insert add(e) offer(e) put(e) offer(e, time, unit) Remove remove() poll() take() poll(time, unit) Examine element() peek() not applicable not applicable
  • 42.
    Interface Deque ▪ Doubleended queue which can support insertion and deletion from both end. ▪ Implementation classes ArrayDeque, ConcurrentLinkedDeque, LinkedBlockingDeque, LinkedList ▪ Application using Deque can be A-steal Job Scheduling,undo task etc
  • 43.
    index ▪ Array Introduction ▪Navigation technique intro ▪ A bit on synchronized ▪ Collection Hierarchy ▪ CollectionVs Collections ▪ List interface ▪ Queue interface ▪ Set Interface. ▪ Map Interface
  • 44.
    Set interface ▪ Duplicateelements wont be allowed. ▪ The duplicity is defined on the implementation of equals() ▪ There is a contract with equals() & hashCode() ▪ Insertion order are normally not preserve. ▪ ListIterator can’t be used to iterate a set ▪ Allowing null depends on implementation classes ▪ NavigableSet,SortedSet are sub interfaces ▪ Important classes are HashSet , LinkedHashSet ,TreeSet, CopyOnWriteArraySet, EnumSet ▪ Guava’s multiset implementation allow duplicate elements
  • 45.
    Hashset ▪ Internally hashtabledata structure ▪ Allow Null ▪ Insertion order does not preserve ▪ Non synchronized Set s = Collections.synchronizedSet(new HashSet(...)); ▪ Iterator return by this class iterator methods are fail-fast ▪ Default Initial capacity =16 load factor =0.75
  • 48.
  • 49.
  • 50.
    TreeSet ▪ Treeset implementsnavigableSset & sortedset. It internally uses treemap. ▪ Element stored in the treeset are sorted in natural order. ▪ Any custom defined class should be a type of comparable because internally compareTo() is used to decide the order. ▪ You will get NPE if you try to store any null Object. ▪ Non synchronized ▪ Iterators are fail-fast ▪ classCastExpcetion ▪ Slower than hashset
  • 53.
    index ▪ Array Introduction ▪Navigation technique intro ▪ A bit on synchronized ▪ Collection Hierarchy ▪ CollectionVs Collections ▪ List interface ▪ Queue interface ▪ Set Interface ▪ Map Interface
  • 54.
    Map interface ▪ Storesthe elements in Key-Value pair / Entry. ▪ Key can’t be duplicate but the values can. ▪ Storing the different value for exiting key will override the previous and returns old key ▪ Not a part of collection framework but provides 3 different collection views to get list of key object ,list of values object and list of entry ▪ Different methods available in this interface are put ,get, remove ,containsKey ,containsValue, keyset, values, entrySet ,putIfAbsent,compute ,clear etc. ▪ A map can’t contains itself to a key but it can be a value of itself. ▪ Implementation classes includes Hashtable, HashMap, ConcurrentHashMap, ConcurrentSkipListMap, IdentityHashMap, LinkedHashMap, Properties, RenderingHints,TreeMap, WeakHashMap etc
  • 56.
    Hashtable ▪ This classimplements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. ▪ initial capacity and load factor ▪ hash collision ▪ It is synchronized .performance is lower than HashMap. ▪ Null is not allowed for both key & value ▪ Iterating over hashtable for(Map.Entry m:hm.entrySet()) {System.out.println(m.getKey() +" "+m.getValue()); }
  • 57.
    HashMap ▪ public classHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable{….} ▪ Underlying data structure hashtable ▪ No insertion order ▪ Single Null as key is allowed ▪ Default initial capacity 16 & load factor 0.75 ▪ Non synchronized . ▪ Collections.synchronizedMap(hm_from_map);
  • 60.
    LinkedHashMap ▪ public classLinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> ▪ Underlying datastructure linked list and hashtable. ▪ Unlike hashMap Insertion order preserved ▪ Permits nulls. more than one null as a key will be overridden & there is no effect on insertion order. ▪ Non Synchronized ▪ Iterators are fail-fast.
  • 62.
    WeakHashMap ▪ Hastable basedimplementation with weak keys. ▪ The entry in weakhashmap will automatically removed if its key is no longer in use ▪ Both null key and null values are supported ▪ Non synchronized ▪ Iterators are fail-fast ▪ Default initial capacity is 16 and default load factor is 0.75 ▪ Depending on the current key is garbage collected or not the different methods like size(),IsEmpty() etcof this map implementation may behave differently
  • 64.
    Title and ContentLayout with Chart Principal collection class Base class Base interfaces Allow duplicate elements? Ordered? Sorted? Thread-safe? ArrayList<E> AbstractList<E> List<E> Yes Yes No No LinkedList<E> AbstractSequentialList<E> List<E>; Deque<E> Yes Yes No No Vector<E> AbstractList<E> List<E> Yes Yes No Yes HashSet<E> AbstractSet<E> Set<E> No No No No LinkedHashSet<E> HashSet<E> Set<E> No Yes No No TreeSet<E> AbstractSet<E> Set<E>; NavigableSet<E>; SortedSet<E> No Yes Yes No HashMap<K, V> AbstractMap<K, V> Map<K, V> No No No No LinkedHashMap<K, V> HashMap<K, V> Map<K, V> No Yes No No Hashtable<K, V> Dictionary<K, V> Map<K, V> No No No Yes TreeMap<K, V> AbstractMap<K, V> Map<K, V>; NavigableMap<K, V>; SortedMap<K, V> No Yes Yes No
  • 65.
  • 66.
    Refrances… Oracle Doc :https://docs.oracle.com/javase/8/docs/api/ Stackoverflow https://stackoverflow.com/ Dzone https://dzone.com/articles/ Geesforgeek https://www.geeksforgeeks.org Tutorialspoint http://www.tutorialspoint.com/ JavaPoint : https://www.javatpoint.com
  • 67.