InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
What Are Different Collection Views Provided By Map Interface? |
|
Answer» Map interface provides 3 views of key-values pairs stored in it: All the views can be NAVIGATED using ITERATORS. Map interface provides 3 views of key-values pairs stored in it: All the views can be navigated using iterators. |
|
| 2. |
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 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 |
|
| 3. |
Difference Between Set And List? |
|
Answer» The most NOTICEABLE DIFFERENCES are :
The most noticeable differences are : |
|
| 4. |
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. 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. |
|
| 5. |
Difference Between Hashmap And Hashtable? |
|
Answer» There are SEVERAL differences between HashMap and Hashtable in Java:
There are several differences between HashMap and Hashtable in Java: |
|
| 6. |
Difference Between Vector And Arraylist? |
|
Answer» Lets note down the differences:
Lets note down the differences: |
|
| 7. |
Difference Between Iterator And Enumeration? |
|
Answer» Iterators differ from enumerations in three ways:
Iterators differ from enumerations in three ways: |
|
| 8. |
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. HashMap is collection of key-value pairs whereas HashSet is un-ordered collection of unique elements. That’s it. No need to describe further. |
|
| 9. |
Difference Between Iterator And Listiterator? |
|
Answer» There are three Differences are there:
There are three Differences are there: |
|
| 10. |
Difference Between Treeset And Sortedset? |
|
Answer» SORTEDSET is an INTERFACE which TREESET IMPLEMENTS. SortedSet is an interface which TreeSet implements. |
|
| 11. |
Difference Between Arraylist And Linkedlist? |
Answer»
|
|
| 12. |
How To Make A Collection Read Only? |
|
Answer» USE following methods:
These methods TAKES collection parameter and RETURN a new read-only collection with same elements as in original collection. Use following methods: These methods takes collection parameter and return a new read-only collection with same elements as in original collection. |
|
| 13. |
How To Make A Collection Thread Safe? |
|
Answer» USE below methods:
Above methods take COLLECTION as parameter and RETURN same type of collection which are synchronized and THREAD safe. Use below methods: Above methods take collection as parameter and return same type of collection which are synchronized and thread safe. |
|
| 14. |
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. 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. |
|
| 15. |
What Are Different Ways To Iterate Over A List? |
|
Answer» You can ITERATE over a list using following WAYS: You can iterate over a list using following ways: |
|
| 16. |
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. 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. |
|
| 17. |
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. 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. |
|
| 18. |
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:
Please note that last two approaches will cause a performance hit. 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: Please note that last two approaches will cause a performance hit. |
|
| 19. |
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. 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. |
|
| 20. |
Which Collection Classes Provide Random Access Of It’s Elements? |
|
Answer» ArrayList, HashMap, TREEMAP, Hashtable CLASSES provide RANDOM access to it’s ELEMENTS. ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it’s elements. |
|
| 21. |
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. 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. |
|
| 22. |
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. 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. |
|
| 23. |
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. 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. |
|
| 24. |
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. 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. |
|
| 25. |
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; public boolean add(E e) 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; public boolean add(E e) |
|
| 26. |
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. 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. |
|
| 27. |
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. This question is just like above to test your knowledge of Collections utility class. Use it reverse() method to reverse the list. |
|
| 28. |
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 array 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 array |
|
| 29. |
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. 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. |
|
| 30. |
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. 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. |
|
| 31. |
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. 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. |
|
| 32. |
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:
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: |
|
| 33. |
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. 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. |
|
| 34. |
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. If we use generic class, we don't need typecasting. It is typesafe and checked at compile time. |
|
| 35. |
How To Synchronize List, Set And Map Elements? |
|
Answer» YES, COLLECTIONS class provides methods to make List, SET or Map elements as synchronized:
Yes, Collections class provides methods to make List, Set or Map elements as synchronized: |
|
| 36. |
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. 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. |
|
| 37. |
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 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 |
|
| 38. |
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. 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. |
|
| 39. |
What Is The Difference Between Comparable And Comparator? |
|
Answer» Comparable:
Comparator:
Comparable: Comparator: |
|
| 40. |
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. 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. |
|
| 41. |
What Is The Difference Between Hashmap And Hashtable? |
|
Answer» HashMap:
Hashtable:
HashMap: Hashtable: |
|
| 42. |
What Is The Difference Between Hashmap And Treemap? |
|
Answer» HASHMAP MAINTAINS no ORDER but TREEMAP maintains ASCENDING order. HashMap maintains no order but TreeMap maintains ascending order. |
|
| 43. |
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 HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated but HashMap need to convert into Set to be iterated |
|
| 44. |
What Is The Difference Between Set And Map? |
|
Answer» SET contains VALUES only WHEREAS MAP contains key and values both. Set contains values only whereas Map contains key and values both. |
|
| 45. |
What Is The Difference Between Hashset And Treeset? |
|
Answer» HashSet MAINTAINS no ORDER WHEREAS TreeSet maintains ASCENDING order. HashSet maintains no order whereas TreeSet maintains ascending order. |
|
| 46. |
What Is The Difference Between List And Set? |
|
Answer» List can CONTAIN DUPLICATE elements whereas Set contains only UNIQUE elements. List can contain duplicate elements whereas Set contains only unique elements. |
|
| 47. |
What Is The Difference Between Iterator And Enumeration? |
Answer»
Enumeration:
Iterator: Enumeration: |
|
| 48. |
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:
ListIterator:
Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and backward direction. Iterator: ListIterator: |
|
| 49. |
What Is The Difference Between Arraylist And Linkedlist? |
|
Answer» ArrayList:
LinkedList:
ArrayList: LinkedList: |
|
| 50. |
What Is The Difference Between Arraylist And Vector? |
|
Answer» ArrayList:
ArrayList: Vector: |
|