Java collections framework Interview Questions & Answers

5 avg. rating (100% score) - 1 votes

Java collections framework Interview Questions & Answers

Are you preparing for Java Collection Framework interview?. The Java collections framework called as JCF is a group of interfaces and classes that implement commonly reusable collection data structures. Although referred to as a framework, it works in a manner of a library. The JCF provides both interfaces that define various collections and classes that implement them. Looking for a job can be cumbersome and tiring, especially when you are not aware of how to apply and where to search and how to prepare well for the job interviews. Wisdomjobs framed Java Collection job interview questions and answers to make it easier for your interview preparation. If you are expertise in Java programming language, then multiple job opportunities are available for your reference.

Java Collections Framework Interview Questions

Java collections framework Interview Questions
    1. Question 1. What Is The Difference Between Arraylist And Vector?

      Answer :

      ArrayList:

      • ArrayList is not synchronized.
      • ArrayList is not a legacy class.
      • ArrayList increases its size by 50% of the array size.

      Vector:

      • Vector is synchronized.
      • Vector is a legacy class.
      • Vector increases its size by doubling the array size.

    2. Question 2. What Is The Difference Between Arraylist And Linkedlist?

      Answer :

      ArrayList:

      • ArrayList uses a dynamic array.
      • ArrayList is not efficient for manipulation because a lot of shifting is required.
      • ArrayList is better to store and fetch data.

      LinkedList:

      • LinkedList uses doubly linked list.
      • LinkedList is efficient for manipulation.
      • LinkedList is better to manipulate data.

    3. Question 3. What Is The Difference Between Iterator And Listiterator?

      Answer :

      Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and backward direction.

      Iterator:

      • Iterator traverses the elements in forward direction only.
      • Iterator can be used in List, Set and Queue.

      ListIterator:

      • ListIterator traverses the elements in backward and forward directions both.
      • ListIterator can be used in List only.

    4. Question 4. What Is The Difference Between Iterator And Enumeration?

      Answer :

      Iterator:

      • Iterator can traverse legacy and non-legacy elements.
      • Iterator is fail-fast.
      • Iterator is slower than Enumeration.

      Enumeration:

      • Enumeration can traverse only legacy elements.
      • Enumeration is not fail-fast.
      • Enumeration is faster than Iterator.

    5. Question 5. What Is The Difference Between List And Set?

      Answer :

      List can contain duplicate elements whereas Set contains only unique elements.

    6. Question 6. What Is The Difference Between Hashset And Treeset?

      Answer :

      HashSet maintains no order whereas TreeSet maintains ascending order.

    7. Question 7. What Is The Difference Between Set And Map?

      Answer :

      Set contains values only whereas Map contains key and values both.

    8. Question 8. What Is The Difference Between Hashset And Hashmap?

      Answer :

      HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated but HashMap need to convert into Set to be iterated

    9. Question 9. What Is The Difference Between Hashmap And Treemap?

      Answer :

      HashMap maintains no order but TreeMap maintains ascending order.

    10. Question 10. What Is The Difference Between Hashmap And Hashtable?

      Answer :

      HashMap:

      • HashMap is not synchronized.
      • HashMap can contain one null key and multiple null values.

      Hashtable:

      • Hashtable is synchronized.
      • Hashtable cannot contain any null key or null value.

    11. Question 11. What Is The Difference Between Collection And Collections?

      Answer :

      Collection is an interface whereas Collections is a class. Collection interface provides normal functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements.

    12. Question 12. What Is The Difference Between Comparable And Comparator?

      Answer :

      Comparable:

      • Comparable provides only one sort of sequence.
      • It provides one method named compareTo().
      • It is found in java.lang package.
      • If we implement Comparable interface, actual class is modified.

      Comparator:

      • Comparator provides multiple sort of sequences.
      • It provides one method named compare().
      • it is found in java.util package.
      • Actual class is not modified.

    13. Question 13. What Is The Advantage Of Properties File?

      Answer :

      If you change the value in properties file, you don't need to recompile the java class. So, it makes the application easy to manage.

    14. Question 14. What Does The Hashcode() Method?

      Answer :

      The hashCode() method returns a hash code value (an integer number). The hashCode() method returns the same integer number, if two keys (by calling equals() method) are same.

      But, it is possible that two hash code numbers can have different or same keys

    15. Question 15. Why We Override Equals() Method?

      Answer :

      The equals method is used to check whether two objects are same or not. It needs to be overridden if we want to check the objects based on property. For example, Employee is a class that has 3 data members: id, name and salary. But, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals() method.

    16. Question 16. How To Synchronize List, Set And Map Elements?

      Answer :

      Yes, Collections class provides methods to make List, Set or Map elements as synchronized:

      • public static List synchronizedList(List l){}
      • public static Set synchronizedSet(Set s){}
      • public static SortedSet synchronizedSortedSet(SortedSet s){}
      • public static Map synchronizedMap(Map m){}
      • public static SortedMap synchronizedSortedMap(SortedMap m){}

    17. Question 17. What Is The Advantage Of Generic Collection?

      Answer :

      If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.

    18. Question 18. What Is Hash-collision In Hashtable And How It Is Handled In Java?

      Answer :

      Two different keys with the same hash value is known as hash-collision. Two different entries will be kept in a single hash bucket to avoid the collision

    19. Question 19. What Is The Dictionary Class?

      Answer :

      The Dictionary class provides the capability to store key-value pairs.

    20. Question 20. What Is The Default Size Of Load Factor In Hashing Based Collection?

      Answer :

      The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

    21. Question 21. What Is The Java Collection Framework? List Down Its Advantages?

      Answer :

      By definition, a collection is an object that represents a group of objects. Like in set theory, a set is group of elements. Easy enough !!

      Prior to JDK 1.2, JDK has some utility classes such as Vector and HashTable, but there was no concept of Collection framework. Later from JDK 1.2 onwards, JDK felt the need of having a consistent support for reusable data structures. Finally, the collections framework was designed and developed primarily by Joshua Bloch, and was introduced in JDK 1.2.

      Its most noticeable advantages can be listed as:

      • Reduced programming effort due to ready to use code
      • Increased performance because of high-performance implementations of data structures and algorithms
      • Provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth
      • Easy to learn APIs by learning only some top level interfaces and supported operations

    22. Question 22. Why Collection Interface Does Not Extend Cloneable And Serializable Interface?

      Answer :

      Well, simplest answer is “there is no need to do it“. Extending an interface simply means that you are creating a subtype of interface, in other words a more specialized behavior and Collection interface is not expected to do what Cloneable and Serializable interfaces do.

      Another reason is that not everybody will have a reason to have Cloneable collection because if it has very large data, then every unnecessary clone operation will consume a big memory. Beginners might use it without knowing the consequences.

      Another reason is that Cloneable and Serializable are very specialized behavior and so should be implemented only when required. For example, many concrete classes in collection implement these interfaces. So if you want this feature. use these collection classes otherwise use their alternative classes.

    23. Question 23. Why Map Interface Does Not Extend Collection Interface?

      Answer :

      A good answer to this interview question is “because they are incompatible“. Collection has a method add(Object o). Map can not have such method because it need key-value pair. There are other reasons also such as Map supports keySet, valueSet etc. Collection classes does not have such views.

      Due to such big differences, Collection interface was not used in Map interface, and it was build in separate hierarchy.

    24. Question 24. Why We Use List Interface? What Are Main Classes Implementing List Interface?

      Answer :

      A java list is a “ordered” collection of elements. This ordering is a zero based index. It does not care about duplicates. Apart from methods defined in Collection interface, it does have its own methods also which are largely to manipulate the collection based on index location of element. These methods can be grouped as search, get, iteration and range view. All above operations support index locations.

      The main classes implementing List interface are: Stack, Vector, ArrayList and LinkedList. Read more about them in java documentation.

    25. Question 25. How To Convert An Array Of String To Arraylist?

      Answer :

      This is more of a programmatic question which is seen at beginner level. The intent is to check the knowledge of applicant in Collection utility classes. For now, lets learn that there are two utility classes in Collection framework which are mostly seen in interviews i.e. Collections and Arrays.

      Collections class provides some static functions to perform specific operations on collection types. And Arrays provide utility functions to be performed on array types.

      //String array
      String[] words = {"ace", "boom", "crew", "dog", "eon"};
      //Use Arrays utility class
      List wordList = Arrays.asList(words);
      //Now you can iterate over the list
      Please not that this function is not specific to String class, it will return List of element of any type, of which the array is. e.g.

      //String array
      Integer[] nums = {1,2,3,4};
      //Use Arrays utility class
      List numsList = Arrays.asList(nums);

    26. Question 26. How To Reverse The List?

      Answer :

      This question is just like above to test your knowledge of Collections utility class. Use it reverse() method to reverse the list.
      Collections.reverse(list);

    27. Question 27. Why We Use Set Interface? What Are Main Classes Implementing Set Interface?

      Answer :

      It models the mathematical set in set theory. Set interface is like List interface but with some differences. First, it is not ordered collection.So no ordering is preserved while adding or removing elements. The main feature it does provide is “uniqueness of elements“. It does not support duplicate elements.

      Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements.

      Based on above reasons, it does not have operations based on indexes of elements like List. It only has methods which are inherited by Collection interface.

      Main classes implementing Set interface are : EnumSet, HashSet, LinkedHashSet, TreeSet.

    28. Question 28. How Hashset Store Elements?

      Answer :

      You must know that HashMap store key-value pairs, with one condition i.e. keys will be unique. HashSet uses Map’s this feature to ensure uniqueness of elements. In HashSet class, a map declaration is as below:

      private transient HashMap<E,Object> map;
      //This is added as value for each key
      private static final Object PRESENT = new Object();
      So when you store a element in HashSet, it stores the element as key in map and “PRESENT” object as value. (See declaration above).

      public boolean add(E e)
      {
      return map.put(e, PRESENT)==null;
      }

    29. Question 29. What Are Collections And Arrays Classes?

      Answer :

      Collections and Arrays classes are special utility classes to support collection framework core classes. They provide utility functions to get read-only/ synchronized collections, sort the collection on various ways etc.

      Arrays also helps array of objects to convert in collection objects. Arrays also have some functions which helps in copying or working in part of array objects.

    30. Question 30. What Is Comparable And Comparator Interface?

      Answer :

      In java. all collection which have feature of automatic sorting, uses compare methods to ensure the correct sorting of elements. For example classes which use sorting are TreeSet, TreeMap etc.

      To sort the data elements a class needs to implement Comparator or Comparable interface. That’s why all Wrapper classes like Integer,Double and String class implements Comparable interface.

      Comparable helps in preserving default natural sorting, whereas Comparator helps in sorting the elements in some special required sorting pattern. The instance of comparator if passed usually as collection’s constructor argument in supporting collections.

    31. Question 31. What Is Queue And Stack, List Down Their Differences?

      Answer :

      A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations.

      Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner.

      Stack is also a form of Queue but one difference, it is LIFO (last-in-first-out).

      Whatever the ordering used, the head of the queue is that element which would be removed by a call to remove() or poll(). Also note that Stack and Vector are both synchronized.

      Usage: Use a queue if you want to process a stream of incoming items in the order that they are received.Good for work lists and handling requests.

      Use a stack if you want to push and pop from the top of the stack only. Good for recursive algorithms.

    32. Question 32. What Is Blockingqueue?

      Answer :

      A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

      BlockingQueue methods come in four forms: one throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up.

    33. Question 33. Which Collection Classes Provide Random Access Of It’s Elements?

      Answer :

      ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it’s elements.

    34. Question 34. What Is Unsupportedoperationexception?

      Answer :

      This exception is thrown on invoked methods which are not supported by actual collection type.

      For example, if you make a read-only list list using “Collections.unmodifiableList(list)” and then call add() or remove() method, what should happen. It should clearly throw UnsupportedOperationException.

    35. Question 35. How To Avoid Concurrentmodificationexception While Iterating A Collection?

      Answer :

      You should first try to find another alternative iterator which are fail-safe. For example if you are using List and you can use ListIterator. If it is legacy collection, you can use enumeration.

      If above options are not possible then you can use one of three changes:

      • If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.
      • You can convert the list to an array and then iterate on the array.
      • You can lock the list while iterating by putting it in a synchronized block.

      Please note that last two approaches will cause a performance hit.

    36. Question 36. What Is Difference Between Fail-fast And Fail-safe?

      Answer :

      You have understood fail-fast in previous question. Fail-safe iterators are just opposite to fail-fast. They never fail if you modify the underlying collection on which they are iterating, because they work on clone of Collection instead of original collection and that’s why they are called as fail-safe iterator. Iterator of CopyOnWriteArrayList is an example of fail-safe Iterator also iterator written by ConcurrentHashMap keySet is also fail-safe iterator and never throw ConcurrentModificationException.

    37. Question 37. What Do You Understand By Iterator Fail-fast Property?

      Answer :

      Fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. Structural changes means adding, removing or updating any element from collection while one thread is Iterating over that collection. Fail-fast behavior is implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws ConcurrentModificationException.

    38. Question 38. What Are Different Ways To Iterate Over A List?

      Answer :

      You can iterate over a list using following ways:

      • Iterator loop.
      • For loop.
      • For loop (Advance).
      • While loop.

    39. Question 39. Why There Is Not Method Like Iterator.add() To Add Elements To The Collection?

      Answer :

      The sole purpose of an Iterator is to enumerate through a collection. All collections contain the add() method to serve your purpose. There would be no point in adding to an Iterator because the collection may or may not be ordered. And add() method can not have same implementation for ordered and unordered collections.

    40. Question 40. How To Make A Collection Thread Safe?

      Answer :

      Use below methods:

      • Collections.synchronizedList(list);
      • Collections.synchronizedSet(set);
      • Collections.synchronizedMap(map);

      Above methods take collection as parameter and return same type of collection which are synchronized and thread safe.

    41. Question 41. How To Make A Collection Read Only?

      Answer :

      Use following methods:

      • Collections.unmodifiableList(list);
      • Collections.unmodifiableSet(set);
      • Collections.unmodifiableMap(map);

      These methods takes collection parameter and return a new read-only collection with same elements as in original collection.

    42. Question 42. Difference Between Arraylist And Linkedlist?

      Answer :

      • LinkedList store elements within a doubly-linked list data structure. ArrayList store elements within a dynamically resizing array.
      • LinkedList allows for constant-time insertions or removals, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list. ArrayLists, on the other hand, allow random access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap.
      • LinkedList has more memory overhead than ArrayList because in ArrayList each index only holds actual object (data) but in case of LinkedList each node holds both data and address of next and previous node.

    43. Question 43. Difference Between Treeset And Sortedset?

      Answer :

      SortedSet is an interface which TreeSet implements.

    44. Question 44. Difference Between Iterator And Listiterator?

      Answer :

      There are three Differences are there:

      • We can use Iterator to traverse Set and List and also Map type of Objects. But List Iterator can be used to traverse for List type Objects, but not for Set type of Objects.
      • By using Iterator we can retrieve the elements from Collection Object in forward direction only whereas List Iterator, which allows you to traverse in either directions using hasPrevious() and previous() methods.
      • ListIterator allows you modify the list using add() remove() methods. Using Iterator you can not add, only remove the elements.

    45. Question 45. Difference Between Hashmap And Hashset?

      Answer :

      HashMap is collection of key-value pairs whereas HashSet is un-ordered collection of unique elements. That’s it. No need to describe further.

    46. Question 46. Difference Between Iterator And Enumeration?

      Answer :

      Iterators differ from enumerations in three ways:

      • Iterators allow the caller to remove elements from the underlying collection during the iteration with its remove() method. You can not add/remove elements from a collection when using enumerator.
      • Enumeration is available in legacy classes i.e Vector/Stack etc. whereas Iterator is available in all modern collection classes.
      • Another minor difference is that Iterator has improved method names e.g. Enumeration.hasMoreElement() has become Iterator.hasNext(), Enumeration.nextElement() has become Iterator.next() etc.

    47. Question 47. Difference Between Vector And Arraylist?

      Answer :

      Lets note down the differences:

      • All the methods of Vector is synchronized. But, the methods of ArrayList is not synchronized.
      • Vector is a Legacy class added in first release of JDK. ArrayList was part of JDK 1.2, when collection framework was introduced in java.
      • By default, Vector doubles the size of its array when it is re-sized internally. But, ArrayList increases by half of its size when it is re-sized.

    48. Question 48. Difference Between Hashmap And Hashtable?

      Answer :

      There are several differences between HashMap and Hashtable in Java:

      • Hashtable is synchronized, whereas HashMap is not.
      • Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
      • The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not.

    49. Question 49. Difference Between List And Map?

      Answer :

      Perhaps most easy question. List is collection of elements where as map is collection of key-value pairs. There is actually lots of differences which originate from first statement. They have separate top level interface, separate set of generic methods, different supported methods and different views of collection.

    50. Question 50. Difference Between Set And List?

      Answer :

      The most noticeable differences are :

      • Set is unordered collection where List is ordered collection based on zero based index.
      • List allow duplicate elements but Set does not allow duplicates.
      • List does not prevent inserting null elements (as many you like), but Set will allow only one null element.

    51. Question 51. When To Use Hashmap Or Treemap?

      Answer :

      HashMap is well known class and all of us know that. So, I will leave this part by saying that it is used to store key-value pairs and allows to perform many operations on such collection of pairs.

      TreeMap is special form of HashMap. It maintains the ordering of keys which is missing in HashMap class. This ordering isby default “natural ordering”. The default ordering can be override by providing an instance of Comparator class, whose compare method will be used to maintain ordering of keys.

      Please note that all keys inserted into the map must implement the Comparable interface (this is necessary to decide the ordering). Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any keys k1 and k2 in the map. If the user attempts to put a key into the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers), the put(Object key, Object value) call will throw a ClassCastException

    52. Question 52. What Are Different Collection Views Provided By Map Interface?

      Answer :

      Map interface provides 3 views of key-values pairs stored in it:

      • key set view
      • value set view
      • entry set view

      All the views can be navigated using iterators.


Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Spring MVC Framework Tutorial