Posts

Showing posts with the label Java Collection Framework

Collection details in Java

Image
How can you get synchronized standard collection objects? Using the static methods synchronizedMap() and synchronizedList() of the Collections class. These methods return the synchronized decorator of the passed collection. However, manual synchronization is still required in the case of a collection traversal. Map m = Collections.synchronizedMap(new HashMap()); List l = Collections.synchronizedList(new ArrayList()); Since Java 6, JCF has been extended with special collections that support multithreading, such as CopyOnWriteArrayList and ConcurrentHashMap. How do I get a read-only collection? With help: Collections.unmodifiableList(list); Collections.unmodifiableSet(set); Collections.unmodifiableMap(map). These methods take a collection as a parameter and return a read-only collection with the same elements inside. Single threaded program that causes the collection to throw a ConcurrentModificationException. public static void main(String[] args) { List<Inte...

TreeSet, HashSet, LinkedHashSet in Java

Image
Difference between TreeSet and HashSet TreeSet provides an ordered storage of elements in a red-black tree. The complexity of performing basic operations is no worse than O(log(N)) (Logarithmic time). HashSet uses the same approach for storing elements as HashMap, with the difference that in HashSet the element itself acts as a key and value, in addition, HashSet does not support ordered storage of elements and provides time complexity of performing operations similar to HashMap. What happens if you add items to the TreeSet in ascending order? TreeSet is based on a red-black tree that can balance itself. As a result, the TreeSet doesn't care in what order you add elements to it, the benefits of this data structure will be preserved. Difference between LinkedHashSet and HashSet LinkedHashSet differs from HashSet only in that it is based on LinkedHashMap instead of HashMap. This makes the order of elements when traversing the collection is identical to the order of insertion of...

HashMap details in Java

Image
When can element in HashMap be lost? Let's say that not a primitive is used as a key, but an object with several fields. After adding an element to the HashMap, one field of the object that acts as a key is changed, which is involved in calculating the hash code. As result, when trying to find a given element by the original key, the correct bucket will be accessed, but equals will no longer find the specified key in the list of elements. Nevertheless, even if equals is implemented in such a way that changing this field of the object does not affect the result, then after increasing the size of the buckets and recalculating the hash codes of the elements, the specified element, with the changed field value, with a high degree of probability will end up in a completely different bucket and then it will be completely lost. Why can't byte[] be used as key in HashMap? The hash code of an array does not depend on the elements stored in it, but is assigned when the array is create...

HashMap in Java

Image
Work of HashMap HashMap consists of buckets. Technically speaking, "buckets" are array elements that hold references to lists of items. When a new key-value pair is added, it calculates the key hash-code, on the basis of which the bucket number (array cell number), into which the new element will fall, is calculated. If the bucket is empty, then a link to the newly added element is saved in it, but if there is already an element there, then there is a sequential transition through the links between the elements in the chain, in search of the last element, from which the link to the newly added element is placed. If an element with the same key was found in the list, then it is replaced. According to Knuth and Cormen, there are two main hash table implementations: open addressing and chaining based. HashMap is implemented using chaining method i.e. each cell of the array (bucket) has its own linked list, and when a collision occurs, a new element is added to this list. For...

HashMap, WeakHashMap, LinkedHashMap in Java

Image
Difference between HashMap and WeakHashMap There are 4 types of references in Java: strong reference, SoftReference, WeakReference, and PhantomReference. Features of each type of links are related to the work of the Garbage Collector. If the object can only be reached using the WeakReference chain (that is, there are no strong and soft references to it), then this object will be marked for deletion. WeakHashMap is a data structure that implements the Map interface and relies on the use of a WeakReference to store keys. Thus, the key/value pair will be removed from the WeakHashMap if the key object is no longer strongly referenced. As an example of using such a data structure, we can cite the following situation: let's say there are objects that need to be extended with additional information, while changing the class of these objects is undesirable or impossible. In this case, we add each object to the WeakHashMap as a key, and the required information as a value. Thus, as long ...

HashMap, Hashtable, IdentityHashMap in Java

Image
Why is HashMap needed if there is a Hashtable? The methods of the Hashtable class are synchronized, which leads to a performance hit, but the HashMap is not; Hashtable cannot contain null elements, whereas a HashMap can contain one null key and any number of null values; Iterator for HashMap, unlike Enumeration for Hashtable, works on the "fail-fast" principle (throws an exception in case of any data inconsistency). Hashtable is a deprecated class. Difference between HashMap and IdentityHashMap IdentityHashMap is a data structure that also implements the Map interface and uses reference comparison when comparing keys (values), rather than calling the equals() method. In other words, in IdentityHashMap, two keys k1 and k2 will be considered equal if they point to the same object, i.e. the condition k1 == k2 is satisfied. IdentityHashMap does not use the hashCode() method, instead of which the System.identityHashCode() method is used, for this reason IdentityHashMap ha...

Queue and Deque interfaces in Java

Image
Comparison of Queue and Deque interfaces. Queue is a queue, which is usually (but not necessarily) built on the FIFO (First-In-First-Out) principle - accordingly, the element is retrieved from the beginning of the queue, and the element is inserted at the end of the queue. Although this principle is violated, for example, PriorityQueue, using "natural ordering" or passed Comparator when inserting a new element. Deque (Double Ended Queue) extends Queue and according to the documentation, it is a linear collection that supports insertion/retrieval of elements from both ends. In addition, implementations of the Deque interface can be built on the FIFO or LIFO principle. Both Deque and Queue implementations usually do not override equals() and hashCode() methods, but instead use the inherited methods of the Object class based on reference comparison. Why does LinkedList implement both List and Deque? LinkedList allows elements to be added to the beginning and end of the list...

ArrayList and LinkedList in Java, memory usage and speed

Image
How much extra memory is needed when calling ArrayList.add()? If there is enough space in the array to accommodate a new element, then no additional memory is required. Otherwise, a new array is created, 1.5 times larger than the existing one (this is true for JDK above 1.7, in earlier versions the size of the increase is different). How much extra memory is allocated when you call LinkedList.add()? One new instance of the nested Node class is created. How much memory to store one byte primitive in LinkedList? Each LinkedList element stores a link to the previous element, the next element, and a data link. private static class Node<E> { E item; Node<E> next; Node<E> prev; //... } For 32-bit systems, each link is 32 bits (4 bytes). The object (header) of the nested Node class itself takes 8 bytes. 4 + 4 + 4 + 8 = 20 bytes, and since the size of each object in Java is a multiple of 8, so we get 24 bytes. A byte primitive occupies 1 by...

ArrayList and LinkedList in Java

Image
How is ArrayList different from Vector? Why added an ArrayList if there was already a Vector? The Vector class methods are synchronized, but ArrayList is not; By default, Vector doubles its size when the memory allocated for the elements runs out. ArrayList only increases its size by half. Vector is a deprecated class and its use is deprecated. How is ArrayList different from LinkedList? In what cases is it better to use the first, and in what cases the second? ArrayList is an array based list, while LinkedList is a classic doubly linked list based on objects with links between them. ArrayList: access to an arbitrary element by index in constant time O(1); access to elements by value in linear time O(N); insertion at the end is performed on average in constant time O(1); removing an arbitrary item from the list takes a long time since in this case, all elements located "to the right" are shifted one cell to the left (the real size of the array (capacity) does not...

Iterator interface in Java

Image
Difference between Enumeration and Iterator Although both interfaces are designed to traverse collections, there are significant differences between them: you cannot add/remove elements using Enumeration; fixed method names in Iterator to improve code readability (Enumeration.hasMoreElements() corresponds to Iterator.hasNext(), Enumeration.nextElement() corresponds to Iterator.next(), etc.); Enumeration is found in legacy classes such as Vector/Stack, while Iterator is found in all modern collection classes. How are Iterable and Iterator related The Iterable interface has only one method, iterator(), which returns an Iterator. How are Iterable, Iterator, and "for-each" related Classes that implement the Iterable interface can be used in a for-each construct that uses an Iterator. Comparison of Iterator and ListIterator ListIterator extends the Iterator interface; ListIterator can only be used to iterate over the elements of the List collection; The Iterator all...

Fail-fast and fail-safe behavior in Java

Image
Fail-fast behavior means that when an error or condition occurs that can lead to an error, the system immediately stops further work and notifies about it. Using a fail-fast approach avoids non-deterministic program behavior over time. In the Java Collections API, some iterators behave like fail-fast and throw a ConcurrentModificationException if the collection was modified after it was created, i.e. added or removed an item directly from the collection, rather than using iterator methods. This behavior is implemented by counting the number of modifications to the collection (modification count): when the collection changes, the modification counter also changes; when creating an iterator, the current value of the counter is passed to it; each time the iterator is accessed, the stored counter value is compared with the current one, and if they do not match, an exception is thrown. Difference between fail-fast and fail-safe In contrast to fail-fast, fail-safe iterators do not t...

"Collection" in Java

Image
"Collection" is a data structure, a collection of some objects. Data (objects in a set) can be numbers, strings, objects of custom classes, etc. Main JCF interfaces and their implementations At the top of the hierarchy in the Java Collection Framework are 2 interfaces: Collection and Map . These interfaces divide all collections included in the framework into two parts according to the type of data storage: simple sequential sets of elements and sets of key-value pairs, respectively. Collection interface is extended by interfaces: List is a collection in which duplicate values are allowed. The elements of such a collection are numbered starting from zero and can be accessed by index. Implementations: ArrayList - encapsulates a regular array, the length of which is automatically increased when new elements are added. LinkedList (bi-directional linked list) - consists of nodes, each of which contains both the actual data and two links to the next and previous node....