Java Collections Interview Questions and Answers – JournalDev

    Java Collections Framework is one of the congress of racial equality APIs of coffee program lyric. It ’ second one of the significant topics for java interview questions. here I am listing some crucial java collections consultation questions and answers to help you in the interview. This is directly coming from my 14+ years of know in Java scheduling .

  1. What are Collection related features in Java 8?

    Java 8 has brought major changes in the Collection API. Some of the changes are :

    1. Java Stream API for collection classes for supporting sequential as well as parallel processing
    2. Iterable interface is extended with forEach() default method that we can use to iterate over a collection. It is very helpful when used with lambda expressions because its argument Consumer is a function interface.
    3. Miscellaneous Collection API improvements such as forEachRemaining(Consumer action) method in Iterator interface, Map replaceAll(), compute(), merge() methods.
  2. What is Java Collections Framework? List out some benefits of Collections framework?

    Collections are used in every programming language and initial java release contained few classes for collections : Vector, Stack, Hashtable, Array. But looking at the larger oscilloscope and usage, Java 1.2 came up with Collections Framework that group all the collections interfaces, implementations and algorithm.
    Java Collections have come through a hanker way with the custom of Generics and Concurrent Collection classes for thread-safe operations. It besides includes blocking interfaces and their implementations in coffee coincident package.
    Some of the benefits of collections framework are ;

    • Reduced development effort by using core collection classes rather than implementing our own collection classes.
    • Code quality is enhanced with the use of well tested collections framework classes.
    • Reduced effort for code maintenance by using collection classes shipped with JDK.
    • Reusability and Interoperability
  3. What is the benefit of Generics in Collections Framework?

    coffee 1.5 came with Generics and all collection interfaces and implementations use it heavily. Generics allow us to provide the type of Object that a solicitation can contain, so if you try to add any component of other type it throws compose time error.
    This invalidate ClassCastException at Runtime because you will get the error at compilation. besides Generics make code scavenge since we don ’ t need to use draw and instanceof operator. I would highly recommend to go through Java Generic Tutorial to understand generics in a better way .

  4. What are the basic interfaces of Java Collections Framework?

    collection is the root of the collection hierarchy. A solicitation represents a group of objects known as its elements. The Java platform doesn ’ t provide any direct implementations of this interface. Set is a collection that can not contain duplicate elements. This interface models the mathematical plant abstraction and is used to represent sets, such as the deck of cards. list is an arrange collection and can contain duplicate elements. You can access any element from its index. The list is more like an array with moral force length. A Map is an aim that maps keys to values. A map can not contain duplicate keys : Each key can map to at most one value. Some other interfaces are Queue, Dequeue, Iterator, SortedSet, SortedMap and ListIterator .

  5. Why Collection doesn’t extend Cloneable and Serializable interfaces?

    Collection interface specifies group of Objects known as elements. How the elements are maintained is left up to the concrete implementations of Collection. For example, some Collection implementations like List allow duplicate elements whereas other implementations like Set don ’ metric ton.
    A lot of the Collection implementations have a public clone method. however, it doesn ’ t make sense to include it in all implementations of Collection. This is because Collection is an abstract representation. What matters is the implementation.
    The semantics and the implications of either clone or serializing come into play when dealing with the actual execution ; so concrete implementation should decide how it should be cloned or serialized, or even if it can be cloned or serialized.
    So mandating clone and serialization in all implementations is less flexible and more restrictive. The specific implementation should decide as to whether it can be cloned or serialized .

  6. Why Map interface doesn’t extend Collection interface?

    Although Map interface and its implementations are partially of the Collections Framework, Map is not collections and collections are not Map. Hence it doesn ’ t make sense for Map to extend Collection or vice versa.
    If Map extends Collection interface, then where are the elements ? The map contains key-value pairs and it provides methods to retrieve the list of Keys or values as collection but it doesn ’ thymine match into the “ group of elements ” prototype .

  7. What is an Iterator?

    The Iterator interface provides methods to iterate over any Collection. We can get iterator exemplify from a Collection using iterator ( ) method. Iterator takes the place of enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a solicitation and implements Iterator Design Pattern .

  8. What is difference between Enumeration and Iterator interface?

    enumeration is twice angstrom fast as Iterator and uses very small memory. enumeration is very basic and fits basic needs. But the Iterator is much safer as compared to Enumeration because it always denies other threads to modify the solicitation object which is being iterated by it.
    Iterator takes the place of count in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection that is not possible with Enumeration. Iterator method acting names have been improved to make its functionality clear .

  9. Why there is not method like Iterator.add() to add elements to the collection?

    The semantics are unclear, given that the sign for Iterator makes no guarantees about the order of iteration. note, however, that ListIterator does provide an attention deficit disorder operation, as it does guarantee the order of the iteration .

  10. Why Iterator don’t have a method to get next element directly without moving the cursor?

    It can be implemented on top of stream Iterator interface but since its use will be rare, it doesn ’ t make smell to include it in the interface that everyone has to implement .

  11. What is different between Iterator and ListIterator?

    • We can use Iterator to traverse Set and List collections whereas ListIterator can be used with Lists only.
    • Iterator can traverse in forward direction only whereas ListIterator can be used to traverse in both the directions.
    • ListIterator inherits from Iterator interface and comes with extra functionalities like adding an element, replacing an element, getting index position for previous and next elements.
  12. What are different ways to iterate over a list?

    We can iterate over a list in two different ways – using iterator and using for-each loop .

    
    List strList = new ArrayList<>();
    
    //using for-each loop
    for(String obj : strList){
        System.out.println(obj);
    }
    
    //using iterator
    Iterator it = strList.iterator();
    while(it.hasNext()){
        String obj = it.next();
        System.out.println(obj);
    }
    

    Using iterator is more thread-safe because it makes sure that if underlie list elements are modified, it will throw ConcurrentModificationException .

  13. What do you understand by iterator fail-fast property?

    Iterator fail-fast property checks for any alteration in the structure of the underlying collection everytime we try to get the adjacent element. If there are any modifications found, it throws ConcurrentModificationException. All the implementations of Iterator in Collection classes are fail-fast by blueprint except the coincident solicitation classes like ConcurrentHashMap and CopyOnWriteArrayList .

  14. What is difference between fail-fast and fail-safe?

    Iterator fail-safe property work with the clone of underlying collection, hence it ’ s not affected by any modification in the collection. By design, all the solicitation classes in java.util software are fail-fast whereas collection classes in java.util.concurrent are fail-safe.
    Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException.
    Check this post for CopyOnWriteArrayList Example .

  15. How to avoid ConcurrentModificationException while iterating a collection?

    We can use coincident solicitation classes to avoid ConcurrentModificationException while iterating over a collection, for exemplar CopyOnWriteArrayList rather of ArrayList.
    Check this post for ConcurrentHashMap Example .

  16. Why there are no concrete implementations of Iterator interface?

    Iterator interface announce methods for iterating a collection but its execution is duty of the Collection implementation classes. Every collection classify that returns an iterator for traverse has its own Iterator execution nested class.
    This allows collection classes to chose whether iterator is fail-fast or fail-safe. For model ArrayList iterator is fail-fast whereas CopyOnWriteArrayList iterator is fail-safe .

  17. What is UnsupportedOperationException?

    UnsupportedOperationException is the exception used to indicate that the operation is not supported. It ’ s used extensively in JDK classes, in collections framework java.util.Collections.UnmodifiableCollection throws this exception for all add and remove operations .

  18. How HashMap works in Java?

    HashMap stores key-value pair in Map.Entry static nested class execution. HashMap works on hashing algorithm and uses hashCode ( ) and equals ( ) method in put and get methods. When we call put method acting by passing key-value pair, HashMap uses Key hashCode ( ) with hashing to find out the exponent to store the key-value couple. The entrance is stored in the LinkedList, so if there is an already existing entry, it uses equals ( ) method acting to check if the passed samara already exists, if yes it overwrites the value else it creates a new entrance and stores this key-value introduction. When we call get method acting by passing Key, again it uses the hashCode ( ) to find the index in the array and then consumption equals ( ) method acting to find the correct Entry and return its value. The downstairs image will explain these contingent distinctly. java-hashmap-entry-impl The other significant things to know about HashMap are capacity, load component, doorway resize. HashMap initial default capacity is 16 and load divisor is 0.75. The brink is capacity multiplied by load factor and whenever we try to add an entry if map size is greater than the threshold, HashMap rehashes the contents of the function into a fresh align with a larger capacity. The capability is always the power of 2, thus if you know that you need to store a large count of key-value pairs, for case in caching data from the database, it ’ s a good idea to initialize the HashMap with correct capacity and load factor .

  19. What is the importance of hashCode() and equals() methods?

    HashMap uses the Key object hashCode ( ) and equals ( ) method to determine the index to put the key-value pair. These methods are besides used when we try to get value from HashMap. If these methods are not implemented correctly, two unlike Key ’ south might produce the same hashCode ( ) and equals ( ) output and in that character, rather than storing it at a different localization, HashMap will consider the same and overwrite them. similarly all the collection classes that doesn ’ deoxythymidine monophosphate store double data use hashCode ( ) and equals ( ) to find duplicates, so it ’ second very authoritative to implement them correctly. The execution of equals ( ) and hashCode ( ) should follow these rules .

    • If o1.equals(o2), then o1.hashCode() == o2.hashCode()should always be true.
    • If o1.hashCode() == o2.hashCode is true, it doesn’t mean that o1.equals(o2) will be true.
  20. Can we use any class as Map key?

    We can use any class as Map Key, however following points should be considered before using them .

    • If the class overrides equals() method, it should also override hashCode() method.
    • The class should follow the rules associated with equals() and hashCode() for all instances. Please refer earlier question for these rules.
    • If a class field is not used in equals(), you should not use it in hashCode() method.
    • Best practice for user defined key class is to make it immutable, so that hashCode() value can be cached for fast performance. Also immutable classes make sure that hashCode() and equals() will not change in future that will solve any issue with mutability.
      For example, let’s say I have a class MyKey that I am using for the HashMap key.

      
      //MyKey name argument passed is used for equals() and hashCode()
      MyKey key = new MyKey("Pankaj"); //assume hashCode=1234
      myHashMap.put(key, "Value");
      
      // Below code will change the key hashCode() and equals()
      // but its location is not changed.
      key.setName("Amit"); //assume new hashCode=7890
      
      //below will return null because HashMap will try to look for key
      //in the same index as it was stored but since the key is mutated, 
      //there will be no match and it will return null.
      myHashMap.get(new MyKey("Pankaj")); 
      

      This is the reason why string and Integer are largely used as HashMap keys .

  21. What are different Collection views provided by Map interface?

    Map interface provides three solicitation views :

    1. Set keySet(): Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
    2. Collection values(): Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator’s remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator remove, Collection.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
    3. Set> entrySet(): Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s remove operation, or the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
  22. What is difference between HashMap and Hashtable?

    HashMap and Hashtable both implements Map interface and looks similar, however, there is the following difference between HashMap and Hashtable .

    1. HashMap allows null key and values whereas Hashtable doesn’t allow null key and values.
    2. Hashtable is synchronized but HashMap is not synchronized. So HashMap is better for single threaded environment, Hashtable is suitable for multi-threaded environment.
    3. LinkedHashMap was introduced in Java 1.4 as a subclass of HashMap, so incase you want iteration order, you can easily switch from HashMap to LinkedHashMap but that is not the case with Hashtable whose iteration order is unpredictable.
    4. HashMap provides Set of keys to iterate and hence it’s fail-fast but Hashtable provides Enumeration of keys that doesn’t support this feature.
    5. Hashtable is considered to be legacy class and if you are looking for modifications of Map while iterating, you should use ConcurrentHashMap.
  23. How to decide between HashMap and TreeMap?

    For slip in, delete, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a grouped order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal .

  24. What are similarities and difference between ArrayList and Vector?

    ArrayList and Vector are similar classes in many ways .

    1. Both are index based and backed up by an array internally.
    2. Both maintains the order of insertion and we can get the elements in the order of insertion.
    3. The iterator implementations of ArrayList and Vector both are fail-fast by design.
    4. ArrayList and Vector both allows null values and random access to element using index number.

    These are the differences between ArrayList and Vector .

    1. Vector is synchronized whereas ArrayList is not synchronized. However if you are looking for modification of list while iterating, you should use CopyOnWriteArrayList.
    2. ArrayList is faster than Vector because it doesn’t have any overhead because of synchronization.
    3. ArrayList is more versatile because we can get synchronized list or read-only list from it easily using Collections utility class.
  25. What is difference between Array and ArrayList? When will you use Array over ArrayList?

    Arrays can contain primitive or Objects whereas ArrayList can contain entirely Objects.
    Arrays are fixed-size whereas ArrayList size is dynamic.
    Arrays don ’ triiodothyronine provide a lot of features like ArrayList, such as addAll, removeAll, iterator, etc. Although ArrayList is the obvious option when we work on the list, there are a few times when an array is good to use .

    • If the size of list is fixed and mostly used to store and traverse them.
    • For list of primitive data types, although Collections use autoboxing to reduce the coding effort but still it makes them slow when working on fixed size primitive data types.
    • If you are working on fixed multi-dimensional situation, using [][] is far more easier than List>
  26. What is difference between ArrayList and LinkedList?

    ArrayList and LinkedList both implement number interface but there are some differences between them .

    1. ArrayList is an index based data structure backed by Array, so it provides random access to its elements with performance as O(1) but LinkedList stores data as list of nodes where every node is linked to its previous and next node. So even though there is a method to get the element using index, internally it traverse from start to reach at the index node and then return the element, so performance is O(n) that is slower than ArrayList.
    2. Insertion, addition or removal of an element is faster in LinkedList compared to ArrayList because there is no concept of resizing array or updating index when element is added in middle.
    3. LinkedList consumes more memory than ArrayList because every node in LinkedList stores reference of previous and next elements.
  27. Which collection classes provide random access of its elements?

    ArrayList, HashMap, TreeMap, Hashtable, and Vector classes provide random access to its elements. Download java collections pdf for more information .

  28. What is EnumSet?

    java.util.EnumSet is Set implementation to use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. EnumSet is not synchronized and null elements are not allowed. It besides provides some utilitarian methods like copyOf ( Collection cytosine ), of ( E first, E… respite ) and complementOf ( EnumSet randomness ). Check this post for coffee enum tutorial .

  29. Which collection classes are thread-safe?

    Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread-safe and can be used in multi-threaded environment. Java 1.5 Concurrent API included some collection classes that allows modification of collection while iteration because they work on the ringer of the collection, so they are safe to use in multi-threaded environment .

  30. What are concurrent Collection Classes?

    Java 1.5 Concurrent software ( java.util.concurrent ) contains thread-safe collection classes that allow collections to be modified while iterating. By plan Iterator execution in java.util packages are fail-fast and throws ConcurrentModificationException. But Iterator implementation in java.util.concurrent packages are fail-safe and we can modify the collection while iterating. Some of these classes are CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet. Read these posts to learn about them in more detail .

    • Avoid ConcurrentModificationException
    • CopyOnWriteArrayList Example
    • HashMap vs ConcurrentHashMap
  31. What is BlockingQueue?

    java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieve and removing an component, and wait for space to become available in the line up when adding an element. BlockingQueue interface is partially of the java collections model and it ’ s primarily used for implementing the producer-consumer trouble. We don ’ t need to worry about waiting for the space to be available for producer or object to be available for consumers in BlockingQueue as it ’ s handled by execution classes of BlockingQueue. Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue, etc.
    Check this military post for practice of BlockingQueue for producer-consumer problem .

  32. What is Queue and Stack, list their differences?

    Both Queue and Stack are used to store data before processing them. java.util.Queue is an interface whose implementation classes are confront in java coincident package. Queue allows recovery of chemical element in First-In-First-Out ( FIFO ) order but it ’ s not constantly the case. There is besides Deque interface that allows elements to be retrieved from both end of the line up.
    The push-down list is similar to queue except that it allows elements to be retrieved in Last-In-First-Out ( LIFO ) order.
    Stack is a class that extends Vector whereas Queue is an interface .

  33. What is Collections Class?

    java.util.Collections is a utility class consists entirely of static methods that operate on or return collections. It contains polymorphous algorithms that operate on collections, “ wrappers ”, which return a new collection backed by a stipulate solicitation, and a few other odds and ends. This class contains methods for collection framework algorithm, such as binary star search, sorting, shuffling, change by reversal, etc .

  34. What is Comparable and Comparator interface?

    Java provides a comparable interface which should be implemented by any custom classify if we want to use Arrays or Collections sorting methods. The comparable interface has a compareTo ( T obj ) method which is used by sorting methods. We should override this method in such a way that it returns a veto integer, zero, or a convinced integer if “ this ” object is less than, peer to, or greater than the object passed as an argument. But, in most real-life scenarios, we want sorting based on different parameters. For exemplar, as a CEO, I would like to sort the employees based on Salary, an HR would like to sort them based on age. This is the situation where we need to use Comparator interface because Comparable.compareTo(Object o) method execution can sort based on one field only and we can ’ metric ton choose the field on which we want to sort the Object. Comparator interface compare(Object o1, Object o2) method acting want to be implemented that takes two Object argument, it should be implemented in such a way that it returns veto int if the first argumentation is less than the second one and returns zero if they are equal and positive int if the first gear argument is greater than the second one. Check this post for use of comparable and Comparator interface to sort objects .

  35. What is difference between Comparable and Comparator interface?

    comparable and Comparator interfaces are used to sort collection or array of objects. comparable interface is used to provide the natural classification of objects and we can use it to provide sorting based on one logic.
    Comparator interface is used to provide different algorithm for sorting and we can choose the comparator we want to use to sort the given collection of objects .

  36. How can we sort a list of Objects?

    If we need to sort an array of Objects, we can use Arrays.sort(). If we need to sort a number of objects, we can use Collections.sort(). Both these classes have overloaded kind ( ) methods for natural classify ( using Comparable ) or sorting based on criteria ( using Comparator ).
    Collections internally uses Arrays sorting method, so both of them have same operation except that Collections take erstwhile to convert list to array .

  37. While passing a Collection as argument to a function, how can we make sure the function will not be able to modify it?

    We can create a read-only collection using Collections.unmodifiableCollection(Collection c) method before passing it as controversy, this will make sure that any operation to change the collection will throw UnsupportedOperationException .

  38. How can we create a synchronized collection from given collection?

    We can use Collections.synchronizedCollection(Collection c) to get a synchronize ( thread-safe ) solicitation backed by the specified collection .

  39. What are common algorithms implemented in Collections Framework?

    Java Collections Framework provides algorithm implementations that are normally used such as sorting and searching. Collections class contain these method implementations. Most of these algorithm function on List but some of them are applicable for all kinds of collections.
    Some of them are sorting, searching, shuffling, min-max values .

  40. What is Big-O notation? Give some examples?

    The Big-O notation describes the operation of an algorithm in terms of the number of elements in a datum structure. Since collection classes are data structures, we normally tend to use Big-O note to chose the collection execution to use based on time, memory and performance. exercise 1 : ArrayList get(index i) is a constant-time mathematical process and doesn ’ t depend on the phone number of elements in the list. So its operation in Big-O notation is O ( 1 ).
    case 2 : A linear search on range or list performance is O ( normality ) because we need to search through entire list of elements to find the element .

  41. What are best practices related to Java Collections Framework?

    • Chosing the right type of collection based on the need, for example if size is fixed, we might want to use Array over ArrayList. If we have to iterate over the Map in order of insertion, we need to use LinkedHashMap. If we don’t want duplicates, we should use Set.
    • Some collection classes allows to specify the initial capacity, so if we have an estimate of number of elements we will store, we can use it to avoid rehashing or resizing.
    • Write program in terms of interfaces not implementations, it allows us to change the implementation easily at later point of time.
    • Always use Generics for type-safety and avoid ClassCastException at runtime.
    • Use immutable classes provided by JDK as key in Map to avoid implementation of hashCode() and equals() for our custom class.
    • Use Collections utility class as much as possible for algorithms or to get read-only, synchronized or empty collections rather than writing own implementation. It will enhance code-reuse with greater stability and low maintainability.
  42. What is Java Priority Queue?

    PriorityQueue is an boundless line up based on a precedence pile and the elements are ordered in their natural order or we can provide Comparator for ordering at the time of universe. PriorityQueue doesn ’ thyroxine allow nothing values and we can ’ thyroxine add any object that doesn ’ deoxythymidine monophosphate provide natural order or we don ’ t have any comparator for them for ordering. Java PriorityQueue is not thread-safe and provide O ( log ( nitrogen ) ) time for enqueing and dequeing operations. Check this post for java precedence line up model .

  43. Why can’t we write code as List numbers = new ArrayList();?

    Generics doesn ’ metric ton documentation sub-typing because it will cause issues in achieving type safety. That ’ south why List is not considered as a subtype of List where S is the super-type of T. To understanding why it’s not allowed, let’s see what could have happened if it has been supported.

    
    List listLong = new ArrayList();
    listLong.add(Long.valueOf(10));
    List listNumbers = listLong; // compiler error
    listNumbers.add(Double.valueOf(1.23));
    

    As you can see from above code that IF generics would have been supporting sub-typing, we could have well add a double to the list of Long that would have caused ClassCastException at runtime while traversing the list of Long .

  44. Why can’t we create generic array? or write code as List[] array = new ArrayList[10];

    We are not allowed to create generic arrays because array carry type information of its elements at runtime. This information is used at runtime to throw ArrayStoreException if elements type doesn ’ thyroxine peer to the defined type. Since generics type information gets erased at compose time by Type Erasure, the range store check would have been passed where it should have failed. Let ’ s sympathize this with a dim-witted case code .

    
    List[] intList = new List[5]; // compile error
    Object[] objArray = intList;
    List doubleList = new ArrayList();
    doubleList.add(Double.valueOf(1.23));
    objArray[0] = doubleList; // this should fail but it would pass because at runtime intList and doubleList both are just List
    

    Arrays are covariant by nature i.e S [ ] is a subtype of T [ ] whenever S is a subtype of T but generics doesn ’ thyroxine subscribe covariance or sub-typing as we saw in the survive motion. then if we would have been allowed to create generic arrays, because of type expunction we would not get an array memory exception even though both types are not related. To know more about Generics, read Java Generics Tutorial .

source : https://gauday.com
Category : interview

We will be happy to hear your thoughts

Leave a reply

GauDay Crypto news and market tracking in real time
Logo
Enable registration in settings - general