1. Collection Framework all in one
Collections
Types of Iterators in Java
There are four types of iterators or cursors available in Java. They are as follows:
1. Enumeration: Enumeration is the first iterator that was introduced in Java 1.0 version. It is located in java.util package. It is a legacy interface that is implemented to get elements one by one from the legacy collection classes such as Vector and Properties.
Methods of Enumeration
1. public boolean hasMoreElements():When this method is implemented, hasMoreElements() will return true If there are still more elements to extract and false if all the elements have been enumerated.
2. public Object nextElement(): The nextElement() method returns next element in the enumeration. It will throw NoSuchElementException when the enumeration is complete
2. Iterator : An iterator in Java is a special type of object that provides sequential (one by one) access to the elements of a collection object.
Iterator Methods in Java
1. public boolean hasNext():
2. public Object next():
3. public void remove():
Difference between Enumeration and Iterator
- Both are useful to retrieve elements from a collection. But the main difference between Enumeration and iterator is with respect to functionality.
- By using an enumeration, we can perform only read access but using an iterator, we can perform both read and remove operation.
2. ListIterator : ListIterator in Java works for iteration in both forward as well as backward directions, therefore, it is called a bi-directional Iterator.
4. Spilterator (Java 1.8)
There are several similarities between Iterator and ListIterator cursors. They are as:
Both are introduced in Java 1.2 version.
Both are Iterators that are used to iterate elements of a collection object.
Both support read and delete operations.
Both support forward direction iteration.
Both are not legacy interfaces.
These old classes are known as legacy classes. The legacy classes defined by java.util are Vector, Hashtable, Properties, Stack, and Dictionary. There is one legacy interface called Enumeration.
List
- A List is an ordered collection of elements where each element has an index.
- It allows duplicate elements.
- You can access elements by their index.
- It allows for storing many null elements.
List can be used when we want to allow or store duplicate elements.
It can be used when we want to store null elements.
When we want to preserve my insertion order, we should go for list.
Set
- Set Represents a collection of unique elements.
- Set does not allow duplicates element.
- Sets and Maps does not maintain any order of element.
- Most of the set implementations allow adding only one null element.
Map
- It represents an object that stores and retrieves elements in the form of a Key/Value pairs.
- A Map is a collection of key-value pairs, where each key is unique.
- It does not allow duplicate keys, but values can be duplicated.
- Does not maintain any order of key-value pairs.
Summary
List maintains the order of elements and allows duplicates.
Set ensures uniqueness of elements and does not maintain any specific order.
Map associates unique keys with values, allowing efficient lookup based on keys.
Similarly, we can get the synchronized version of Set, Map objects by using the following syntax:
Synchronization of ArrayList using Collections.synchronizedList() method
public static Set synchronizedList( Set s );
public static Map synchronizedList( Map m );
Fail-Fast
fail-fast approach prioritizes the detection of errors as soon as they occur, which can help in diagnosing and debugging issues more easily. It's a proactive strategy to maintain system integrity and prevent further damage or inconsistency when errors are detected.
--------
List
1. ArrayList
1. ArrayList is a resizable array or growable array that means the size of ArrayList can increase or decrease in size at runtime. Once ArrayList is created, we can add any number of elements.
2. Index-based structure: It uses an index-based structure in java.
3. Duplicate elements: Duplicate elements are allowed in the array list.
4. Null elements: Any number of null elements can be added to ArrayList.
5. Insertion order: It maintains the insertion order in Java. That is insertion order is preserved.
7. Synchronized: ArrayList is not synchronized. That means multiple threads can use the same ArrayList objects simultaneously.
8. Synchronization of ArrayList using Collections.synchronizedList() method
USe of Arraylist
- We want to store duplicate elements.
- We want to store null elements.
- It is more preferred in Java when getting of the element is more as compared to adding and removing elements.
- We are not working in the multi-threading environment in Java because ArrayList is non-synchronized.
- we can make arraylist synchronize using synchronizedList and CopyOnWriteArrayList class in Java.
2. LinkedList
- LinkedList in Java is a linear data structure that uses a doubly linked list internally to store a group of elements.
- Java LinkedList class allows storing duplicate elements.
- Null elements can be added to the linked list.
- Heterogeneous elements are allowed in the linked list.
- Java LinkedList is not synchronized.
- Insertion and removal of elements in the LinkedList are fast as compare to Arraylist.
2. Set
When to use Set?
1. If you want to represent a group of individual elements as a single entity where duplicates are not allowed and insertion order is not preserved then we should go for the Set.
2. If your requirement is to get unique elements, set is the best choice for this.
3. If you want to remove duplicate elements without maintaining the insertion order from the non-set collection, you should go for set.
1. HashSet in Java
- Insertion order not maintain.
- duplicate element not allow. Only unique element.
- not synchronized.
- HashSet is an implementation class of the set interface in Java.
- It stores unique elements only.
- It allows null values.
- It does not maintain the order of elements in which we add.
- It is not thread-safe.
- To create a HashSet, we need to import the java.util.HashSet package.
- HashSet is not thread-safe, so we should not use it in multi-threaded applications.
- HashSet has a time complexity of O(1) on average for adding an element.
- HashSet in Java is an unordered collection of elements (objects) that contains only unique elements. That is, it allows duplicate free elements to be stored.
- It internally uses Hashtable data structure to store a set of unique elements. It is much faster and gives constant-time performance for searching and retrieving elements.
1. The underlying data structure of HashSet is Hashtable. A hash table stores data by using a mechanism called hashing.
2. HashSet does not allow duplicate elements. If we try to add a duplicate element in HashSet, the older element would be overwritten.
3. It allows only one null element. If we try to add more than one null element, it would still return only one null value.
4. HashSet does not maintain any order in which elements are added. The order of the elements will be unpredictable. It will return in any random order.
5. It is much faster due to the use of hashing technique and gives constant-time performance for adding (insertion), retrieval, removal, contains, and size operations.
Hashing provides constant execution time for methods like add(), remove(), contains(), and size() even for the large set.
6. HashSet class is not synchronized which means it is not thread-safe. Therefore, multiple threads can use the same HashSet object at the same time and will not give the deterministic final output.
If you want to synchronize HashSet, use Collections.synchronizeSet() method.
7. The iterator returned by HashSet class is fail-fast which means any modification that happened in the HashSet during iteration, will throw ConcurrentModificationException.
When to use HashSet in Java?
We don’t want to store duplicate elements.
We want to remove duplicate elements from the list.
HashSet is more preferred when add and remove operations are more as compared to get operations.
We are not working in a multithreading environment.
points
HashSet is an implementation class of the set interface in Java.
It stores unique elements only.
It allows null values.
It does not maintain the order of elements in which we add.
It is not thread-safe.
To create a HashSet, we need to import the java.util.HashSet package.
HashSet is not thread-safe, so we should not use it in multi-threaded applications.
HashSet has a time complexity of O(1) on average for adding an element.
We cannot use primitive data types in a hash set. So, we need to use their corresponding wrapper classes.
2. LinkedHashSet
points
- It does not allow to insert of duplicate elements.
- LinkedHashSet class contains unique elements .
- allow to insert null element.
- not-synchronized means not thread-safe.
- maintain the insertion order.
- It is slightly slower than HashSet.
1. Java LinkedHashSet class contains unique elements like HashSet. It does not allow to insert of duplicate elements. If we try to add a duplicate element, it will fail and the iteration order of the set is not modified.
2. LinkedHashSet class permits to insert null element.
3. LinkedHashSet class in Java is non-synchronized. That means it is not thread-safe.
4. LinkedHashSet class preserve the insertion order of elements
5. It is slightly slower than HashSet.
6. Linked hash set is very efficient for insertion and deletion of elements
LinkedHashSet is an ordered variant of HashSet that internally uses a linked list to store the elements in the set.
It combines the properties of both Set and LinkedList.
LinkedHashSet stores unique elements only, it does not allow duplicate elements in the set.
It maintains the insertion order of elements, i.e., the order in which elements were added to the set.
LinkedHashSet implements the set interface, meaning that it inherits all the methods of the set interface, such as add(), remove(), contains(), and size().
It also implements the Serializable and Cloneable interfaces.
It provides several methods to manipulate the elements in the set, such as add(), addAll(), remove(), removeAll(), retainAll(), contains(), size(), isEmpty(), clear(), toArray(), iterator(), spliterator(), stream(), parallelStream(), and toString().
3. TreeSet in Java
Features of TreeSet class in Java
1. Java TreeSet contains unique elements similar to the HashSet. It does not allow the addition of a duplicate element.
2. The access and retrieval times are quite fast.
3. TreeSet does not allow inserting null element.
4. TreeSet class is non-synchronized. That means it is not thread-safe.
5. TreeSet maintains the ascending order. When we add elements into the collection in any order, the values are automatically presented in sorted, ascending order.
6. Java TreeSet internally uses a TreeMap for storing elements.
When to Use TreeSet?
- TreeSet can be used when we want unique elements in sorted order.
Which is better to use: HashSet or TreeSet?
- If you want to store unique elements in sorted order then use TreeSet, otherwise, use HashSet with no ordering of elements. This is because HashSet is much faster than TreeSet.
Map in Java
- A map in Java is a container object that stores elements in the form of key and value pairs. A key is a unique element (object) that serves as an “index” in the map.
1. HashMap
Features of Java HashMap class
- In HashMap, insertion order is not maintain.
- HashMap contains only unique keys that means no duplicate keys are allowed but values can be duplicated. We retrieve values based on the key.
- HashMap can have only one null key because duplicate keys are not allowed.
- Multiple null values are allowed in the HashMap.
- not synchronized
- best for search Operation.
8. HashMap in Java is not synchronized that means while using multiple threads on the HashMap object, we will get unreliable results.
9. Java HashMap implements Cloneable, and Serializable interfaces but not implements Random Access.
10. HashMap is the best choice if our frequent operation is a search operation.
11. If no element exists in the HashMap, it will throw an exception named
1. The underlying data structure of HashMap is HashTable. In simple words, HashMap internally uses hash table for storing entries. That means accessing and adding an entry almost as fast as accessing an array.
2. In HashMap, insertion order is not preserved (i.e. maintains no order). Which means we cannot retrieve keys and values in the same order in which they have been inserted into the HashMap.
3. It is based on the Hashcode of keys, not on the hash code of values.
4. Java HashMap contains only unique keys that means no duplicate keys are allowed but values can be duplicated. We retrieve values based on the key.
5. Heterogeneous objects are allowed for both keys and values.
6. Java HashMap can have only one null key because duplicate keys are not allowed.
7. Multiple null values are allowed in the HashMap.
8. HashMap in Java is not synchronized that means while using multiple threads on the HashMap object, we will get unreliable results.
9. Java HashMap implements Cloneable, and Serializable interfaces but not implements Random Access.
10. HashMap is the best choice if our frequent operation is a search operation.
11. If no element exists in the HashMap, it will throw an exception named
2. LinkedHashMap
- it maintain the insertion order.
- allows only one null key but can have multiple null values.
- not synchronized
-
1. The underlying data structure of LinkedHashMap is HashTable and LinkedList.
2. Java LinkedHashMap maintains the insertion order. The entries in Java LinkedHashMap can be retrieved either in the order in which they were inserted into the map (known as insertion order) or in the order in which they were last accessed, from least to most recently accessed.
3. LinkedHashMap contains unique elements. It contains values based on keys.
4. LinkedHashMap allows only one null key but can have multiple null values.
5. LinkedHashMap in Java is non synchronized. That is, multiple threads can access the same LinkedHashMap object simultaneously.
6. The default initial capacity of LinkedHashMap class is 16 with a load factor of 0.75.
3. TreeMap
- in Java is a concrete class that is a red-black tree based implementation of the Map interface. It provides an efficient way of storing key/value pairs in sorted order automatically and allows rapid retrieval. It was added in JDK 1.2 and present in java.util.TreeMap.
- A TreeMap implementation provides guaranteed log(n) time performance for checking, adding, retrieval, and removal operations.
- The two main differences between HashMap and TreeMap is that
1. HashMap is an unordered collection of elements while TreeMap is sorted in the ascending order of its keys. The keys are sorted either using Comparable interface or Comparator interface.
2. HashMap allows only one null key while TreeMap does not allow any null key.
1. The underlying data structure of Java TreeMap is a red-black binary search tree.
2. TreeMap contains only unique elements.
3. TreeMap cannot have a null key but can have multiple null values.
4. Java TreeMap is non synchronized. That means it is not thread-safe. We can create a synchronized version of map by calling Collections.synchronizedMap() on the map.
5. TreeMap in Java maintains ascending order. The mappings are sorted in treemap either according to the natural ordering of keys or by a comparator that is provided during the object creation of TreeMap depending upon the constructor used.
HashTable
- hashtable contains the data in key-value pair & each key-value pair is known as entry.
- In hashtable, key should always be unique but values can be duplicate
- Hashtable can store heterogeneous elements or different type of elements at key positive.
- We cannot store null value in Hashtable
- Hashtable does not follows the insertion & sorting order.
- Hashtable are synchronized data- Structure.
- The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
Concurrent Hashmap (2 ascept : race condition , concurrent modification exception)
Map
| extends
ConcurrentMap
| extends
ConcurrentNavigableMap Serializable
| implement
ConcurrentHashMap
- ConcurrentHashMap is a thread-safe implementation of the Map interface in Java, which means multiple threads can access it simultaneously without any synchronization issues.
-One of the key features of the ConcurrentHashMap is that it provides fine-grained locking, meaning that it locks only the portion of the map being modified, rather than the entire map.
-In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updated in the object, the thread must lock the particular segment in which the thread wants to operate. This type of locking mechanism is known as Segment locking or bucket locking. Hence at a time, 16 update operations can be performed by threads.
-Inserting null objects is not possible in ConcurrentHashMap as a key or value.
- It provides a thread-safe implementation of hashmap.
- It designed to allow multiple threads to access and modify the map concurrently without need for explicit synchronization.
- This makes it well-suited for scenarios where high concurrency is required and difference thread need to access and manipulate the map concurrently.
Internal Working
- Segmented or bucket or fine-grained locking.this locking mechanism concurrent hashmap follow.
-1. ConcurrentHashMap achieves high concurrency by dividing its data into segments or partitions, each acting as an indepenedent hash table. (Hashmap internal dataStructure is an Array)
-2. Read operation are fully concurrent , allowing multiple threads to read simultaneously from the same or different segments.
-3. Write operations are synchronized at the segment level to ensure thread safety during updates.( here every segement has lock so cannot write & there is no way to override).
-4. It provides total concurrency for reads, allowing multiple threads to read without blocking.
-5. Unlike Hashtable, ConcurrentHashMap lock only the affected segment during write operation, preventing unncecessary contention. ( During write operation there only one segment are lock other free to read )
-6.This results in better performance and throughput in multi-threaded environments.
-7.Any number of threads can perform READ operation but for WRITE in object, the thread must lock the particular segment in which the thread wants to operate.
Differenct between Concurrent HahsMap and Collections.synchronizedMap() ?
1. Concurrent HashMap
2. Collections.synchronizedMap()
1. ConcurrentHashMap designed for high level concurrency. Divides the map to segments, where each can be locked independently.
1. synchronizedMap() has lower concurrency. Uses a single monitor to synchronize access to the entire map.
2. Performance better in high-concurrency scenarious.
2. Lower performance due to coarse-grained locking.
3. Thread can access element without causing a ConcurrentModificationException during the iteration.
3. During iteration, if the underlying map is modified by another thread. It may result in a ConcurrentModificationException .
4. Does not support null in key or values.
4. Null support depends on the input Map.
5.ConcurrentHashMap follow Fine-grained locking, enables concurrent access to differenct segments.
5. Coarse-grained locking , locks the entire map for each operation.
Difference between HashMap and ConcurrentHashMap
- HashMap is the Class which is under Traditional Collection and ConcurrentHashMap is a Class which is under Concurrent Collections, apart from this there are various differences between them which are:
- HashMap is non-Synchronized in nature i.e. HashMap is not Thread-safe whereas ConcurrentHashMap is Thread-safe in nature.
- HashMap performance is relatively high because it is non-synchronized in nature and any number of threads can perform simultaneously. But ConcurrentHashMap performance is low sometimes because sometimes Threads are required to wait on ConcurrentHashMap.
- While one thread is Iterating the HashMap object, if other thread try to add/modify the contents of Object then we will get Run-time exception saying ConcurrentModificationException.Whereas In ConcurrentHashMap we wont get any exception while performing any modification at the time of Iteration.
-What are several Thread-safe classes provided by Java Collections framework?
Answer: Several Thread-safe classes in Java Collections framework are as follows:
Stack
Properties
Vector
Hashtable
BlockingQueue
ConcurrentMap
ConcurrentNavigableMap
Differenect between TreeSet and TreeMap
1. TreeSet implements SortedSet in Java.
TreeMap implements Map Interface in Java
2. TreeSet stored a single object in java.
TreeMap stores two Object one Key and one value.
3. TreeSet does not allow duplication Object in java.
TreeMap in java allows duplication of values.
4. TreeSet implements NavigableSet in Java.
TreeMap implements NavigableMap in Java.
5. TreeSet is sorted based on objects.
TreeMap is sorted based on keys.
Comments
Post a Comment