Difference between HashSet and CopyOnWriteArraySet with Example

I have already shared how HashSet works internally in java . Both HashSet and CopyOnWriteArraySet does not allow duplicates . In this post we will learn about the differences , similarities between HashSet and CopyOnWriteArraySet.

Read Also :  WebServices Interview Questions in Java 

Difference between HashSet and CopyOnWriteArraySet in Java

1. Synchronization :  HashSet is not synchronized . CopyOnWriteArraySet is synchronized. Synchronization means at a time only one thread can access the object.

2. Performance :  HashSet is faster as it is not synchronized. That means many threads can execute the same piece of code simultaneously. In comparison , CopyOnWriteArraySet is slower.

3. Fail-fast vs Fail-safe : Iterators returned by HahSet's iterator and listiterator  methods are fail-fast. CopyOnWriteArraySet uses fail-safe iterator . We have already shared the fail-fast vs fail-safe iterators in java with example

4. ConcurrentModificationException : HashSet can throw ConcurrentModificationException  while CopyOnWriteArraySet can not .

How LinkedHashMap Works Internally in Java

Please go through how HashMap works internally in java first before reading further about the internal working of  LinkedHashMap.

Interviewer : What is LinkedHashMap ?

LinkedHashMap is the Hashtable (synchronized HashMap) and linkedlist implementation of the Map interface , with predictable iteration order.

Read Also : HashSet  Interview questions

Interviewer :Why do we need LinkedHashMap when we already had TreeMap and HashMap ?

TreeMap and HashMap classes were added in java 1.2 , while LinkedHashMap was added to jdk in java version 1.4  .
HashMap provides constant time performance for basic operations like (add, remove and contains) method but elements are unordered.  In TreeMap elements are naturally sorted but there is increased cost associated with it. Performance of the basic operations (get, remove or put)  in TreeMap is slower in comparison i.e log(n) time.
So, LinkedHashMap addition removes the chaotic ordering provided by HashMap, without incurring the increased cost associated with TreeMap.

Internal Working of LinkedHashMap in Java