Questions d'entretien de Java Collection

What is EnumSet? EnumSet in Java is a specialized set implementation for use with enum types. All of the elements stored in an enum set must, explicitly or implicitly, come from a single enum type that is specified while creating the set. EnumSet was introduced in Java 5 along with the Enum. One of the things to note about EnumSet is that it is an abstract class and uses factory methods to create objects. There are two concrete implementations of EnumSet - RegularEnumSet JumboEnumSet

HashSet Vs LinkedHashSet Vs TreeSet in Java HashSet is unordered, it will store elements on the basis of the calculated hash that's it. LinkedHashSet maintains the insertion order of the elements. TreeSet keeps the element in sorted order. The sorting order,s TreeSet follows by default is known as the natural ordering of the elements. HashSet as well as LinkedHashSet allow null value to be stored. Mind you only one null value is allowed in both HashSet and LinkedHashSet. TreeSet does not allow null value, trying to add null to a TreeSet will result in a null pointer exception. For HashSet and LinkedHashSet comparison of the elements is done using equals() method. Note that set allows only unique elements, and that uniqueness is maintained by using the equals() method to compare elements. TreeSet does the comparison of the element using the compareTo (or compare) method, depending on whether sorting is done using Comparable or Comparator. Performance wise HashSet is at the top as it has no added baggage of insertion ordering or sorting. If hashing is done correctly HashSet offers constant time performance O(1) for the basic operations (add, remove, contains and size). For LinkedHashSet performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list. TreeSet has to sort elements with every insertion so that way performance is slow, but TreeSet provides guaranteed log(n) time cost for the basic operations (add, remove and contains) irrespective of the number of elements stored. How Does HashSet internally works in Java? HashSet internally uses HashMap to store it's elements. But it differs from HashMap on two points. HashSet only stores unique values i.e. no duplicates are allowed. In HashSet we have add(E e) method which takes just the element to be added as parameter not the (key, value) pair. Refer How HashSet works internally in Java to know more about the internal implementation of the HashSet.

Which Set implementation should be used if you want the insertion order to be maintained? LinkedHashSet should be used in this case. Refer LinkedHashSet in Java to know more about LinkedHashSet in Java.

What is LinkedHashSet? LinkedHashSet is also one of the implementation of the Set interface. Actually LinkedHashSet class extends the HashSet and has no other methods of its own. LinkedHashSet also stores unique elements just like other implemetations of the Set interface. How LinkedHashSet differs is that it maintains the insertion-order; that is elements in the LinkedHashSet are stored in the sequence in which they are inserted. Note that insertion order is not affected if an element is re-inserted into the set. Which Map implementation should be used if you want to retain the insertion order? LinkedHashMap should be used in this case. Refer LinkedHashMap in Java to know more about LinkedHashMap in Java.

What is LinkedHashMap? LinkedHashMap is also one of the implementation of the Map interface, apart from implementing Map interface LinkedHashMap also extends the HashMap class. So just like HashMap, LinkedHashMap also allows one null key and multiple null values. How it differs from other implementations of the Map interface like HashMap and TreeMap is thatLinkedHashMap maintains the insertion order of the elements which means if we iterate a LinkedHashMap we'll get the keys in the order in which they were inserted in the Map. LinkedHashMap maintains a doubly-linked list running through all of its entries and that's how it maintains the iteration order.

Which Map implementation should be used if you want Map values to be sorted by keys? TreeMap should be used in this case.

What is TreeMap in Java? TreeMap is also one of the implementation of the Map interface like HashMap and LinkedHashMap. TreeMap class implements the NavigableMap interface and extends the AbstractMap class. How it differs from other implementations of the Map interface is that objects in TreeMap are stored in sorted order. The elements are ordered using their natural ordering or a comparator can be provided at map creation time to provide custom ordering. One important point about TreeMap is, though HashMap and LinkedHashMap allow one null as key, TreeMap doesn't allow null as key. Any attempt to add null in a TreeMap will result in a NullPointerException.

What is a WeakHashMap? WeakHashMap is a Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. Which means storing only weak references allows garbage collector to remove the entry (key-value pair) from the map when its key is not referenced outside of the WeakHashMap. In WeakHashMap both null values and the null key are supported. A WeakHashMap is created as- Map weakHashMap = new WeakHashMap();

What is a IdentityHashMap? IdentityHashMap class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). Where as In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)). Note that This class is not a general-purpose Map implementation. While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.

Difference between HashMap and HashTable in Java. Though both HashTable and HashMap store elements as a (key, value) pair and use hashing technique to store elements, moreover from Java v1.2, HashTable class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. But there are certain difference between the two -HashMap is not synchronized where as HashTable is synchronized. HashMap allows one null value as a key and any number of null values where as HashTable does not allow null values either as key or as value. For traversing a HashMap an iterator can be used. For traversing a HashTable either an iterator or Enumerator can be used. The iterator used for both HashMap and HashTable is fail-fast but the enumerator used with HashTable is fail-safe. Performance wise HashMap is faster than the HashTable reason being HashMap is not synchronized.

HashMap Vs LinkedHashMap Vs TreeMap in Java. HashMap makes no guarantees as to the order of the map. LinkedHashMap maintains the insertion order of the elements which means if we iterate a LinkedHashMap we'll get the keys in the order in which they were inserted in the Map. TreeMap stores objects in sorted order. HashMap, as well as LinkedHashMap, allows one null as key, multiple values may be null though. TreeMap does not allow null as key. HashMap stores elements in a bucket which actually is an index of the array. LinkedHashMap also uses the same internal implementation, it also maintains a doubly-linked list running through all of its entries. TreeMap is a Red-Black tree based NavigableMap implementation. Performance wise HashMap provides constant time performance O(1) for get() and put() method. LinkedHashMap also provides constant time performance O(1) for get() and put() method but in general a little slower than the HashMap as it has to maintain a doubly linked list. TreeMap provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

Related blog:

Java program to remove duplicate element from array

Recommended Posts

Questions d'entretien de Java Collection
Collection Java9
Réintroduction Java - Collection Java
[Java] Cadre de collection
Collection expirée de java
Une collection de questions simples pour les débutants Java
Résumé de la collecte des problèmes Java SE 8 Sliver
Collection d'exemples de code parallèle Java
[Java] Comparateur de la classe Collection
Collection de méthodes de code de test Java
Qu'est-ce qu'une collection Java?
Collecte de copies approfondies en Java
Java
Collection de modèles JNA (Java Native Access)
Java
Advance Hibernate Interview Questions et réponses
Java Performance Chapitre 5 Bases de la récupération de place
Importance de l'interface apprise de la collection Java
Top 75+ questions et réponses d'entrevue JSP en 2020
[Java] Comparaison des méthodes d'opération de la collection et de StringBuilder
Java (gestion des exceptions, threading, collection, fichier IO)
[Java] Contenu de l'interface de collection et de l'interface de liste