Collection framework interview question – Collection Framework Interview Questions in Java

Collection framework interview question: List of topic-wise frequently asked java interview questions with the best possible answers for job interviews.

Collection Framework Interview Questions in Java

Question 1.
What are Collection related features in Java 8?
Java 8 has brought major changes in the Collection API. Some of the [ changes are:

  • Java Stream API for collection classes for supporting sequential as well as parallel processing
  • The iterable interface is extended with forEach( 0 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 functional interface.
  • MiscellaneousCollectionAPIimprovementssuchasforEachRemaining(Consumer action) method inlterator interface, Map replaceAll( ), compute( ), merge( ) methods.

Question 2.
what is Java Collections Framework? List out some benefits of the Collections framework?
Collections are used in every programming language and the initial java release contained few classes for collections: Vector, Stack, Hashtable, Array. But looking at the larger scope and usage, Java 1.2 came up with Collections Framework 1 that groups all the collections interfaces, implementations, and algorithms.

Java Collections have come a long way with the usage of Generics and Concurrent Collection classes for thread-safe operations. It also includes blocking interfaces and their implementations in the java concurrent package. Some of the benefits of the 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

Question 3.
What is the benefit of Generics in Collections Framework?
Java 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 collection can contain, so if you try to add an element of another type it throws a compile-time error.

This avoids ClassCastException at Runtime because you will get the error at compilation. Also, Generics make code clean since we don’t need to use casting and instance of operator. I would highly recommend going through Java Generic Tutorial to understand generics in a better way.

Question 4.
What are the basic interfaces of the Java Collections Framework?
The collection is the root of the collection hierarchy. A collection 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 cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards. The list is an ordered collection and can contain duplicate elements.

You can access any element from its index. The list is more like an array with dynamic length. A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Some other interfaces are Queue, Dequeue, Iterator, SortedSet, SortedMap, and Listlterator.

Question 5.
Why Collection doesn’t extend Cloneable and Serializable interfaces?
The collection interface specifies a 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’t. A lot of the Collection implementations have a public clone method. However, it doesn’t really make sense to include it in all implementations of Collection. This is because the Collection is an abstract representation.

Question 6.
What matters is the implementation.
The semantics and the implications of either cloning or serializing come into play when dealing with the actual implementation; so concrete implementation should decide how it should be cloned or serialized, or even if it can be cloned or serialized.

So mandating cloning and serialization in all implementations is actually less flexible and more restrictive. The specific implementation should make the decision as to whether it can be cloned or serialized.

Question 7.
Why Map interface doesn’t extend the Collection interface?
Although Map interfaces and their implementations are part 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 the Collection interface, then where are the elements? The map contains key-value pairs and it provides methods to retrieve a list of Keys or values as Collection but it doesn’t fit into the “group of elements” paradigm.

Question 8.
What is an Iterator?
Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using the 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 collection and implements Iterator Design Pattern.

Question 9.
How do you traverse through a collection using its Iterator?
To use an iterator to traverse through the contents of a collection, follow these steps:

  • Obtain an iterator to the start of the collection by calling the collections iterator( ) method.
  • Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
  • Within the loop, obtain each element by calling next( ).

Question 10.
How do you remove elements during Iteration?
Iterator also has a method remove( ) when remove is called, the current element in the iteration is deleted.

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

Question 12.
Why there is no method like Iterator. add( ) to add elements to the collection?
The semantics are unclear, given that the contract for Iterator makes no guarantees about the order of iteration. Note, however, that Listlterator does provide an add operation, as it does guarantee the order of the iteration.

Question 13.
Why Iterator doesn’t have a method to get the next element directly without moving the cursor?
It can be implemented on top of the current Iterator interface but since its use will be rare, it doesn’t make sense to include it in the interface that everyone has to implement.

Question 14. What is different between Iterator and Listlterator?

  • We can use Iterator to traverse Set and List collections whereas Listlterator can be used with Lists only.
  • Iterator can traverse in forwarding direction only whereas Listlterator can be used to traverse in both directions.
  • Listlterator inherits from the Iterator interface and comes with extra functionalities like adding an element, replacing an element, getting index position for previous and next elements.

Question 15.
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<String> strList = new ArrayList<>( );
//using for-each loop
for(String obj : strList){
//using iterator
lterator<String> it = strList.iterator( );
while (it. hasNext ( )) {
     String obj = );

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

Question 16.
What do you understand by iterator fail-fast property?
Iterator fail-fast property checks for any modification in the structure of the underlying collection everytime we try to get the next element. If there are any modifications found, it throwsConcurrentModificationException. All the implementations of Iterator in Collection classes are fail-fast by design except the . concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.

Question 17.
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 collection classes in java.util package 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.

Question 18.
How to avoid ConcurrentModificationException while iterating a collection?
We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection, for example CopyOnWriteArrayList instead of Array List.

Question 19.
Why there are no concrete implementations of Iterator interface?
Iterator interface declare methods for iterating a collection but it’s implementation is responsibility of the Collection implementation classes. Every collection class that returns an iterator for traversing has it’s own Iterator implementation nested class.
This allows collection classes to chose whether iterator is fail-fast or fail-safe. For example ArrayList iterator is fail-fast whereas CopyOnWriteArrayList iterator is fail-safe.

Question 20.
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.UnmodifiableCollectionthrows this exception for all add and remove operations.

Question 21.
How HashMap works in Java?
HashMap stores key-value pair in Map.Entry static nested class implementation. HashMap works on hashing algorithm and uses hashCode( ) and equals( ) method input and get methods. When we call the put method by passing key-value pair, HashMap uses Key hashCode( ) with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there are already existing entries, it uses the equals( ) method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and stores this key-value Entry.

When we call get method by passing Key, again it uses the hashCode( ) to find the index in the array and then use the equals( 0 methods to find the correct Entry and return it’s value. Below image will explain these details clearly.

Collection Framework Interview Questions in Java chapter 13 img 1

The other important things to know about HashMap are capacity, load factor, threshold resizing. HashMap initial default capacity is 32 and load factor is 0.75. Threshold is capacity multiplied by load factor and whenever we try to add an entry, if map size is greater than threshold, HashMap rehashes the contents of map into a new array with a larger capacity. The capacity is always power of 2, so if you know that you need to store a large number of key-value pairs, for example in caching data from database, it’s good idea to initialize the HashMap with correct capacity and load factor.

Question 22.
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 also used when we try to get value from HashMap. If these methods are not implemented correctly, two different Key’s might produce the same hashCode( ) and equals( ) output and in that case, rather than storing it at different location, HashMap will consider the same and overwrite them.

Similarly all the collection classes that doesn’t store duplicate data use hashCode( ) and equals( ) to find duplicates, so it’s very important to implement them correctly. The implementation of equals( ) and hashCode( ) should follow these rules.

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 own 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.

  • If ol.equals(o2), then ol.hashCode( ) == o2.hashCode0should always be true.
  • If ol.hashCode( ) = = o2.hashCode is true, it doesn’t mean that ol.equals(o2) will be true.

Question 23.
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 the hashCode( ) method.
  • The 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 HashMap key.

//MyKey name argument passed is used for equals( ) and hashCode( ) 
MyKey key = new MyKey(“Pankaj”); //assume hashcode=1234 
myHashMap.putfkey, “value”);
// Below code will change the key hashCode( ) and equals( )
// but it’s 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 key is mutated,
//there will be no match and it will return null. 
myHashMap.getCnew MyKey(“Pankaj”));
  • This is the reason why String and Integer are mostly used as HashMap keys.

Question 24.
What are different Collection views provided by Map interface?
Map interface provides three collection views:
• 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 own 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.

• 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 own 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.

• Set<Map.Entry<K, V» 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 own remove operation, or through 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.

Question 25.
What is the Dictionary class?
The Dictionary class is an abstract class. The class maps keys to values. The classes such as HashTable are the subclasses of the abstract class Dictionary. The key and values are objects. The key and value are non-null objects.

Question 26.
What is the ResourceBundle class?
A ResourceBundle is a group of related subclasses which are sharing the same base name. For example, ButtonLabel is the base name. All the characters following the base name indicates the following elements respectively.

Question 27.
What is the Vector class?
The Vector class implements an incremental array of objects.
The vector components can be accessed using an integer index.
The size of a Vector increases or decreases as needed to accommodate the items.

Question 28.
What is the SimpleTimeZone class?
SimpleTimeZone is a concrete subclass of TimeZone class. The TimeZone class represents a time zone that is to be used with Gregorian calendar.

Question 29.
What is Locale?
A Locale object represents a specific geographical, political, dr cultural region.

Question 30.
How will you load a specific locale?
By ResourceBundle.getBundle(?) method.

Question 31.
What is the difference between Comparable and Comparator?

NO Comparable Comparator
1 Comparable provides only one sort of sequence. The comparator provides multiple sorts of sequences.
2 It provides one method named compareTo( ) It provides one method named compare( )
3 It is found in java.lang package. It is found in java. util package.
4 If we implement a Comparable interface, the actual class is modified. The actual class is not modified.

Question 32.
What is the advantage of Properties file?
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.

Question 33.
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 the same. But, it is possible that two hash code numbers can have different or same keys.

Question 34.
Why do we 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.

Question 35.
How to synchronize List, Set and Map elements?
Yes, Collections class provides methods to make List, Set or Map elements as synchronized:

public static List synchronizedList(List 1)§
public static Set synchronizedSet(Set s)0
public static SortedSet synchronizedSortedSet(SortedSet s){ }
public static Map synchronizedMap(Map m){ }
public static SortedMap synchronizedSortedMap(SortedMap m){ }

Question 36.
What is the advantage of generic collection?
If we use generic class, we don’t need typecasting. It is typesafe and checked at compile time.

Question 37.
What is hash-collision in Hashtable and how it is handled in Java?
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.

Question 38.
What is the Dictionary class?
The Dictionary class provides the capability to store key-value pairs.

Question 39.
What is the default size of the load factor in the hashing-based collection?
The default size of the load factor is 0.75. The default capacity is computed as the initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

Question 40.
Which package is used for pattern matching with regular expressions?
java.util.regex package is used for this purpose.

Question 41.
java.util.regex consists of which classes?
java.util.regex consists of three classes: Pattern class, Matcher class and PatternSyntaxException class.

Question 42.
What is the use of the ‘SimpleDateFormat’ and how can you use it to display the current system date in ‘yyyy/MM/DD HH:mm:ss’ format?
SimpleDateFormat is one such concrete class which is widely used by Java developers for parsing and formatting of dates. This is also used to convert Dates to String and vice-versa.

Literally every Enterprise level Java Application invariably uses the SimpleDateFormat for handling user dates. We of course aren’t expecting Java interviewees to be absolutely spectacular with the syntaxes. But a basic know-how of this class is mandatory.

public class CurrentsystemDate {
public static void main(string[ ] args) {
     SimpleDateFormat sysForm = new SimpleDateFormat(“yyyy/MM/DD HH:mm:ss”);
     Date curdate= new Date( );

Question 43.
What is difference between ArrayList and vector?
1) Synchronization: ArrayList is not thread-safe whereas Vector is thread- safe. In Vector class each method like addO, get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.

2) Data growth: Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

Question 44.
How can Arraylist be synchronized without using Vector?
Arraylist can be synchronized using:
Collection.synchronizedList(List list)
Other collections can be synchronized:
Collection.synchronizedMap(Map map)
Collection. synchronizedCollection(Collection c)

Question 45.
If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeelD of Employee class. What are the steps?

  1. Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeelD
  2. Now call Collections. sort( ) method and pass list as an argument.

Now consider that Employee class is a jar file.

  1. Since the Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object objl) method.
  2. Call Collections. sort( ) on the list and pass comparator as an argument.

Question 46.
What is difference between HashMap and HashTable?
Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
1. Hashmap is not synchronized in nature but hshtable is.
2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.
Fail-safe – if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterators own remove method, the iterator will throw a ConcurrentModificationException?
3. HashMap permits null values and only one null key, while Hashtable doesn’t allow key or value as null.

Question 47.
What are the classes implementing List interface?
There are three classes that implement List interface:

1) ArrayList: It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It, also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.

2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.

3) LinkedList: The LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.

Question 48.
Which all classes implement Set interface?
A Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements el and e2 such that el.equals(e2), and at most one null element. HashSet, SortedSet and TreeSet are the commonly used class which implements Set interface.

SortedSet – It is an interface which extends Set. A the name suggest, the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.

TreeSet – It is the implementation of SortedSet interface. This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.

HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets

Question 49.
What is difference between List and a Set?

  1. The list can contain duplicate values but Set doesn’t allow it. The set allows only to unique elements.
  2. The list allows retrieval of data to be in the same order in the way it is inserted but Set doesn’t ensures the sequence in which data can be retrieved. (Except HashSet)

Question 50.
What is the difference between Arrays and ArrayList?
Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as :

  • int [ ] intArray= new int[6];
  • intArray[7] // will give ArraysOutOfBoundException.
  • Also, the size of the array cannot be incremented or decremented. But with ArrayList the size is variable.

Once the array is created elements cannot be added or deleted from it. But with ArrayList, the elements can be added and deleted at runtime.

List list = new ArrayList( ); 
list.remove(0) // will remove the element from the 1st location.
•       ArrayList is one dimensional but array can be multidimensional.
        int[ ][ ][ ] intArray= new int[3][2][1]; // 3 dimensional array

• To create an array the size should be known or initialized to some value. If not initialized carefully there could be memory wastage. But ArrayList is all about dynamic creation and there is no wastage of memory.

Question 51.
When to use ArrayList or LinkedList?
Adding new elements is pretty fast for either type of list. For the ArrayList, doing random lookup using “get” is fast, but for LinkedList, it’s slow. It’s slow because there’s no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you’re doing random access on the list, and a LinkedList works better if you’re doing a lot of editing in the middle of the list.

Question 52.
Consider a scenario. If an ArrayList has to be iterating to read data only, what are the possible ways, and which is the fastest?
It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using the iterator. Because the value stored in ArrayList is indexed access. So while accessing the value is accessed directly as per the index.

Question 53.
Now another question with respect to the above question is if accessing through iterator is slow then why do we need it and when to use it.
For loop does not allow the updating in the array (add or remove operation) inside the loop whereas Iterator does. Also, an Iterator can be used where there is no clue what type of collections will be used because all collections have an iterator.

Question 54.
Which design pattern Iterator follows?
It follows the Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation. Iterator should be implemented as an interface. This allows the user to implement it anyway it’s easier for him/her to return data. The benefits of Iterator are about their strength to provide a common interface for iterating through collections without bothering about the underlying implementation.

Example of Iteration design pattern – Enumeration The class java. util. Enumeration is an example of the Iterator pattern. It represents an abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds.

Question 55.
Is it better to have a HashMap with a large number of records or n number of small hashMaps?
It depends on the different scenarios one is working on:

  1. If the objects in the hashMap are the same then there is no point in having a different hashmap as they traverse time in a hashmap is invariant to the size of the Map.
  2. If the objects are of different types like one of Person class, other of Animal class, etc then also one can have single hashmap but different hashmap would score over it as it would have better readability.

Question 56.
Why is it preferred to declare: List<String> list = new ArrayList<String> 0> instead of ArrayList<String> = new ArrayList<String>0;
It is preferred because:

  1. If later on, the code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
  2. The most important one – If a function is declared such that it takes a list. E.g. void showDetails(List list); When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector, LinkedList making the function more flexible.

Question 57.
What is the difference between iterator access and index access?
Index-based access allows access of the element directly on the basis of the index. The cursor of the data structure can directly go to the ‘n’ location and get the element. It does not traverse through n-1 elements.
In Iterator-based access, the cursor has to traverse through each element to get the desired element. So to reach the ‘n’th element it needs to traverse through n-1 elements.
Insertion, updation, or deletion will be faster for iterator-based access if the operations are performed on elements present in between the data structure.
Insertion,updating, or deletion will be faster for index-based access if the operations are performed on elements present at the last of the data structure.
Traversal or search in index-based data structure is faster.
ArrayList is index access and LinkedList is iterator access.

Question 58.
How to sort the list in reverse order?
To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverse order( ). Then, pass the reverse Comparator to the sort( ) method.
List list = new ArrayList( );
Comparator comp = Collections.reverseOrder( );
Collections.sort(list, comp)

Question 59.
Can a null element add to a Treeset or HashSet?
A null element can be added only if the set contains one element because when a second element is added then as per set definition a check is made to check duplicate value and comparison with null element will throw NullPointerException. HashSet is based on hashMap and can contain the null elements.

Question 60.
How to sort the list of strings – case insensitive?
Using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

Question 61.
How to Make a List (ArrayList, Vector, LinkedList) read-only?
A list implementation can be made read-only using Collections. unmodifiable list(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.

Question 62.
What is ConcurrentHashMap?
A ConcurrentHashMap is the thread-safe implementation of the Map interface. In this class put and remove methods are synchronized but not the get method. This class is different from Hashtable in terms of locking; it means that hashtable use object-level lock but this class uses bucket-level lock thus having better performance.

Question 63.
Which is faster to iterate LinkedHashSet or LinkedList?

Question 64.
Which data structure HashSet implements
HashSet implements hashmap internally to store the data. The data passed to HashSet is stored as a key in a hashmap with null as a value.

Question 65.
Arrange in the order of speed – HashMap, HashTable, Collections. synchronized map, concurrent hashmap
HashMap is fastest, ConcurrentHashMap, Collections.synchronizedMap, HashTable.

Question 66.
What is an identity hash map?
The IdentityHashMap uses == for equality checking instead of equals( ). This can be used for both performance reasons if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.

Question 67.
What is WeakHashMap?
A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations.

Question 68.
Why Collection interface does not extend the Cloneable and Serializable interface?
There is no need to do it because, extending an interface simply means that you are creating a subtype of the interface, in other words, a more specialized behavior and Collection interface are not expected to do what is Cloneable and Serializable interfaces do.
Another reason is that not everybody will have a reason to have a 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.

Question 69.
Why insertion and deletion in ArrayList are slow compared to LinkedList?
• ArrayList internally uses an array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of the old array is copied to the new array.

• During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node and updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked Mst is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.

Question 70.
Difference between String, StringBuffer, and StringBuilder?

String StringBuffer StringBuilder
The string is an immutable class StringBuffer is a mutable class StringBuilder is a mutable class
The new object is created every time when modified No new object is created, modification is done in the existing one No new object is created, modification is done in the existing one
Syntax – String sl-’hello”; Syntax –

StringBuffer sf=new StringBuffer(“hello”);

Syntax –

StringBuilder sb=new StringBuilder(“hello”);

StringBuffer methods are synchronized. StringBuilder methods are non-synchronized and added in jdk 5.
Use String if you require immutability use StringBuffer in java if you need mutable + thread- safety use StringBuilder in Java if you require mutable + without thread-safety..

How will you sort a collection of String in case-sensitive order?
Use Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Example –

public class stringsortExample{
public static void main(string[ ] args){
           List list = new ArrayList( );
           Col1ections.sort (list);
           Col1ections.sort(list, String.CASE_INSENSITIVE_ORDER);
     Public static void display(List list)
for (string str : list){
                      System.out.print(str + “ “);

Question 72.
What is the difference between poll( ) and remove( ) method of Queue interface?
Though both poll( ) and remove( ) method from Queue is used to remove the object and returns the head of the queue, there is a subtle difference between them. If Queue is empty 0 then a call to remove 0 methods will throw Exception, while a call to poll( ) method returns null. By the way, exactly which element is removed from the queue depends upon the queue’s ordering policy and varies between different implementations, for example, PriorityQueuekeepslowestelementasperComparatoror Comparable ahead position.

Question 73.
How do you remove an entry from a Collection? and subsequently what is the difference between the remove( ) method of Collection and remove( ) method of Iterator, which one you will use while removing elements during iteration?
Collection interface defines remove(Object obj) method to remove objects from Collection. List interface adds another method remove(int index), which is used to remove objects at a specific index. You can use any of these methods to remove an entry from Collection, while not iterating. Things change when you iterate. Suppose you are traversing a List and removing only certain elements based on logic, then you need to use Iterator’s remove( ) method. This method removes the current element from Iterator’s perspective. If you use Collection’s or List’s remove( ) method during iteration then your code will throw Concurrent ModificationException. That’s why it’s advised to use the Iterator remove( ) method to remove objects from Collection.

Question 74.
What is the difference between Synchronized Collection and Concurrent Collection?
Java 5 has added several new Concurrent Collection classes e.g. ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue, etc, which has made Interview questions on Java Collection even trickier. Java Also provided a way to get Synchronized copies of the collection e.g. ArrayList, HashMap by using Collections. synchronizedMapO Utility function.One Significant difference is that Concurrent Collections has better performance than synchronized Collection because they lock only a portion of Map to achieve concurrency and Synchronization.

Question 75.
What do you need to do to use a custom object as a key in Collection classes like Map or Set?
If you are using any custom object in Map as a key, you need to override the equals( ) and hashcode( ) method and make sure they follow their contract. On the other hand, if you are storing a custom object in Sorted Collection e.g. SortedSet or SortedMap, you also need to make sure that your equals( ) method is consistent with the compareTo( ) method, otherwise, that collection will not follow their contacts e.g. Set may allow duplicates.

Question 76,
What is NavigableMap in Java? What is the benefit of Map?
NavigableMap Map was added in Java 1.6, it adds navigation capability to Map data structure. It provides methods like lowqrKey( ) to get keys which is less than the specified key, floor key( ) to return keys that are less than or equal to the specified key, ceilingKey( ) to get keys that is greater than or equal to specified key and, higher key( ) to return keys which are greater specified key from a Map.

It also provides similar methods to get entries e.g. lower entry( ), floor entry( ), ceiling entry( ), and higher entry( )- Apart from navigation methods, it also provides utilities to create sub-Map e.g. creating a Map from entries of an existing Map like trail map, heatmap, and subMap. heatmap ( ) method returns a NavigableMap whose keys are less than specified, tailMapO returns a NavigableMap whose keys are greater than the specified, and subMap( ) gives a NavigableMap between a range, specified by toKey to fromKey.

Question 77.
Which one you will prefer between Array and ArrayList for Storing objects and why?
Though ArrayList is also backed up by array, it offers some usability advantage over array in Java. The array is a fixed-length data structure, once created you cannot change its length. On the other hand, ArrayList is dynamic, it automatically allocates a new array and copies the content of the old array, when it resizes. Another reason for using ArrayList over Array is the support of Generics. Array doesn’t support Generics, and if you store an Integer object on a String array, you will only going to know | about it at runtime, when it throws ArrayStoreException. On the other hand, if you use ArrayList, the compiler and IDE will catch that error on the spot. So if you know the size in advance and you don’t need re-sizing then use an array, otherwise use ArrayList.

Question 78.
Can we replace Hashtable with ConcurrentHashMap?
Yes, we can replace Hashtable with ConcurrentHashMap and that’s what is suggested in the Java documentation of ConcurrentHashMap. but you need to be careful with code that relies on the locking behavior of Hashtable. Since Hashtable locks whole, Map instead of a portion of Map, compound operations like if(Hashtable. get(key) = null) put(key, value) works in Hashtable but not in ConcurrentHashMap. Instead of .this use putlfAbsent( ) method of ConcurrentHashMap

Question 79.
What is CopyOnWriteArrayList, how it is different than ArrayList and Vector?
CopyOnWriteArrayList is a new List implementation introduced in Java 1.5 which provides better concurrent access than Synchronized List. Better concurrency is achieved by Copying ArrayList over each write and replace with original instead
of locking. Also CopyOnWriteArrayList doesn’t throw any ConcurrentModification Exception. It’s different than ArrayList because it’s thread-safe and ArrayList is not thread-safe and it’s different than Vector in terms of Concurrency. CopyOnWriteArrayList provides better Concurrency by reducing contention among readers and writers.

Question 80.
Why Listlterator has added ( ) method but Iterator doesn’t or Why add() method is declared in Listlterator and not on Iterator.
Listlterator has added the ( ) method because of its ability to traverse or iterate in both directions of the collection, it maintains two pointers in terms of previous and next call and is in a position to add a new element without affecting the current iteration.

Question 81.
When does ConcurrentModificationException occur on iteration?
When you remove an object using Collection’s or List’s remove method e.g. remove(Object element) or remove(int index), instead of Iterator’s removed) method than ConcurrentModificationException occurs. As per Iterator’s contract, if it detects any structural change in Collection e.g. adding or removing of element, once Iterator begins, it can throw ConcurrentModificationException.

Question 82.
Difference between Set, List, and Map Collection classes?
java.util.Set, java.util.List and java. util. Map defines three of the most popular data structure support in Java. Set provides a uniqueness guarantee i.e.g you cannot store duplicate elements on it, but it’s not ordered. On the other hand, List is an ordered Collection and also allows duplicates. The map is based on hashing and stores keys and values in an Object called entry. It provides 0(1) performance to get the object if you know keys if there is no collision.

A popular implementation of Set is HashSet, of List are ArrayList and LinkedList, and of Map are HashMap, Hashtable, and ConcurrentHashMap. Another key difference between Set, List, and Map is that Map doesn’t implement a Collection interface, while the other two do. For a more detailed answer, see Set vs List vs Map in Java.

Question 83.
What is BlockingQueue, how it is different than other collection classes?
BlockingQueue is a Queue implementation available in java. util.concurrent package. It’s one of the concurrent Collection classes added on Java 1.5, main difference between BlockingQueue and other collection classes is that apart from storage, it also provides flow control. It can be used in inter-thread communication and also provides built-in thread safety by using a happens-before guarantee. You can use BlockingQueue to solve the Producer-Consumer problem, which is what is needed in most concurrent applications.