Difference between ArrayList and HashSet in Java
Here are couple of differences between ArrayList and HashSet.
- Implementation: Implementation : ArrayList implements List interface while HashSet implements Set interface in Java.
- Internal implementation: ArrayList is backed by an Array while HashSet is backed by an HashMap.
- Duplicates : ArrayList allows duplicate values while HashSet doesn’t allow duplicates values.
- Constructor : ArrayList have three constructor which are ArrayList(), ArrayList(int capacity) ArrayList(int Collection c) while HashSet have four constructor which are HashSet(), HashSet(int capacity), HashSet(Collection c) and HashSet(int capacity, float loadFactor)
- Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn’t maintain any order.
- Indexing : ArrayList is index based we can retrieve object by calling get(index) method or remove objects by calling remove(index) method while HashSet is completely object based. HashSet also does not provide get() method.
- Null Object: ArrayList not apply any restriction, we can add any number of null value while HashSet allow one null value.
9. Basic Operation’s Time complexity :-
9.1 ArrayList common operation’s time complexity
add() – takes O(1) time;
get() – it takes constant time O(1);
remove() –it takes linear time complexity O(n) . It iterate the entire array to find the element qualifying for removal.
contains() – It also take linear time complexity O(n).
9.2 Set common operation’s time complexity
For HashSet, the add(), remove() and contains() operations cost constant O(1) time thanks to the internal HashMap implementation.
- Syntax: ArrayList:-
ArrayList list=new ArrayList();
HashSet set=new HashSet();
[1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5
1 2 3 4
My Personal Notes arrow_drop_up
Please Login to comment...