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 .
5. Added in java version : HashSet class was added in java version 1.2 , while CopyOnWriteArraySet class was added in java version 1.5 (or java 5) .
6. Package : HashSet class is present in java.util package , while CopyOnWriteArraySet class is present in java.util.concurrent package.
Example of ArraySet and CopyOnWriteArraySet in Java
import java.util.HashSet;import java.util.concurrent.CopyOnWriteArraySet;public class HashSetCopyOnWriteArraySetExample { public static void main(String[] args) {
HashSet<String> hsobj = new HashSet<String>(); hsobj.add("Alive is awesome"); hsobj.add("Love yourself"); System.out.println("HashSet object output :"+ hsobj);
CopyOnWriteArraySet<String> coponwrtobj =
new CopyOnWriteArraySet<String>();coponwrtobj.add("Alive is awesome"); coponwrtobj.add("Love yourself"); System.out.println("CopyOnWriteArraySet object output :"+ coponwrtobj);
} }
Output : HashSet object output :[Alive is awesome, Love yourself]
CopyOnWriteArraySet object output :[Alive is awesome, Love yourself]
Similarities between HashSet and CopyOnWriteArraySet
1. Permit null values : Both HashSet and CopyOnWriteArraySet permits null.
2. Java Collections Framework : Both classes are part of the Java Collections Framework.
3. Duplicate elements : Both classes does not allow to store duplicate elements.
When to prefer CopyOnWriteArraySet over HashSet
So, if your code involves multi-threading tasks then prefer CopyOnWriteArraySet over HashSet.
Otherwise , always use HashSet .
Recap : Difference between HashSet and CopyOnWriteArraySet in Java
HashSet | CopyOnWriteArraySet | |
---|---|---|
Synchronized | No | Yes |
Thread-Safe | No | Yes |
Throws ConcurrentModificationException | Yes | No |
Iterator type | Fail fast iterator | Fail safe iterator |
Performance | Fast | Slow in comparision |
Added | Java 1.2 | Java 1.5 |
If you have any other questions or doubts regarding the difference between HashSet and CopyOnWriteArraySet in Java , please mention in comments.