YouTube Icon

Interview Questions.

Java Collections Interview Question and Answers - Jul 15, 2022

fluid

Java Collections Interview Question and Answers

Q1. What is Java Collections Framework? List out a few advantages of Collections framework?

Ans: Collections are utilized in every programming language and preliminary java launch contained few instructions for collections: Vector, Stack,Hashtable, Array. But looking at the larger scope and utilization, Java 1.2 got here up with Collections Framework that organization all the collections interfaces, implementations and algorithms. Java Collections have come via a long way with usage of Generics and Concurrent Collection instructions for thread-safe operations. It additionally includes blocking off interfaces and their implementations in java concurrent bundle. Some of the blessings of collections framework are:

Reduced improvement attempt by means of the usage of core collection training as opposed to enforcing our personal series instructions.

Code nice is greater with the usage of nicely examined collections framework lessons.

Reduced effort for code renovation by way of the use of collection training shipped with JDK.

Reusability and Interoperability

 Q2. Name the middle Collection instructions.

Ans:

AbstractCollection- Implements maximum of the Collection interface.

AbstractList- Extends AbstractCollection and implements List interface.

AbstractSequentialList- Extends AbstractList to offer sequential get entry to.

ArrayList- Extends AbstractList to offer dynamic array implementation.

LinkedList- Extends AbstractSequentialList to implement a linked listing.

AbstractQueue- Extends AbstractCollection and implements Queue interface.

ArrayDeque- Resizable-array implementation of the Deque interface.

PriorityQueue- Extends AbstractQueue to provide a priority-based queue.

AbstractSet- Extends AbstractCollection and implements Set interface.

HashSet- Extends AbstractSet subsidized by means of a HashTable (actually a HashMap instance).

LinkedHashSet- Extends HashSet to provide insertion order interation.

TreeSet- Extends AbstractSet (and implements NavigableSet interface) to offer looked after set.

EnumSet- Extends AbstractSet to be used with Enum factors.

 Q3. What is the benefit of Generics in Collections Framework?

Ans: Java 1.5 came with Generics and all series interfaces and implementations use it heavily. Generics permit us to provide the kind of Object that a collection can incorporate, so if you attempt to upload any element of other kind it throws collect time error. This avoids ClassCastException at Runtime because you may get the error at compilation. Also Generics make code clean due to the fact that we don’t need to apply casting and instanceof operator. It also provides as much as runtime benefit due to the fact the bytecode instructions that do kind checking are not generated.

Q4. What is HashMap and Map?

Ans: Map is Interface that's part of Java collections framework. This is to store Key Value pair, and Hashmap is magnificence that implements that the use of hashing technique.

Q5. What exchange does autoboxing bring to Collection?

Ans: Since we understand that series can not save primitive sorts, best references. Before the creation of autoboxing/unboxing in JDK5, if you desired to strore primitive cost like int in a collection, it needed to be wrapped in an Integer elegance manually. While retrieving the value it needed to be solid manually into its primitive kind.

Collection still shop best references however autoboxing/unboxing facilitate it to manifest automatically, and not using a need to wrap it manually.

List<Integer> tempList = new ArrayList<Integer>();

// Storing in collection using autoboxing

tempList.Upload(1);

// wrapping primitive int 2 to Integer manually, without autoboxing

tempList.Add(new Integer(2));

Q6. What are the simple interfaces of Java Collections Framework?

Ans:

Collection is the basis of the gathering hierarchy. A series represents a group of gadgets referred to as its elements. The Java platform doesn’t provide any direct implementations of this interface.

Set is a collection that can not include replica elements. This interface fashions the mathematical set abstraction and is used to represent sets, consisting of the deck of playing cards.

List is an ordered series and may contain reproduction factors. You can get right of entry to any element from it’s index. List is greater like array with dynamic period.

A Map is an object that maps keys to values. A map can not contain replica keys: Each key can map to at maximum one cost.

Some different interfaces are Queue, Dequeue, Iterator, SortedSet, SortedMap and ListIterator.

Q7. Difference among HashMap and HashTable? Compare Hashtable vs HashMap?

Ans: Both Hashtable and HashMap provide key-fee get right of entry to to statistics. The Hashtable is one of the original collection lessons in Java (additionally called as legacy classes). HashMap is part of the brand new Collections Framework, introduced with Java 2, v1.2. There are several differences among HashMap and Hashtable in Java as indexed below

The HashMap magnificence is more or less equal to Hashtable, besides that it is unsynchronized and allows nulls. (HashMap allows null values as key and price while Hashtable doesn’t allow nulls).

HashMap does not guarantee that the order of the map will stay steady through the years. But certainly one of HashMap's subclasses is LinkedHashMap, so in the occasion which you'd need predictable generation order (that is insertion order by default), you could easily change out the HashMap for a LinkedHashMap. This wouldn't be as easy in case you have been using Hashtable.

HashMap is non synchronized whereas Hashtable is synchronized.

Iterator within the HashMap is fail-speedy even as the enumerator for the Hashtable isn't. So this can be a design attention.

Q8. What is for-each fashion loop?

Ans: Another feature which changed into delivered to Collection with JDK five is for-every style loop. Any collection which wants to be the target of the "for-each loop" announcement has to put into effect iterable interface.

Using for-every loop is easier than constructing the iterator to iterate over the gathering and may be utilized in maximum of the instances in preference to the usage of the iterator loop.

If you have a list of Strings, that may be iterated using for-every loop like this.

For(String town : cityList)    System.Out.Println("Name " + city);

HubSpot Video
 

Q9. Why Collection doesn’t increase Cloneable and Serializable interfaces?

Ans: Collection interface specifies group of Objects called elements. How the factors are maintained is left as much as the concrete implementations of Collection. For instance, a few Collection implementations like List allow reproduction factors while different implementations like Set don’t. A lot of the Collection implementations have a public clone approach. However, it does’t actually make feel to encompass it in all implementations of Collection. This is due to the fact Collection is an abstract illustration. What matters is the implementation.

The semantics and the implications of either cloning or serializing come into play whilst handling the real implementation; so concrete implementation ought to determine how it ought to be cloned or serialized, or even if it is able to be cloned or serialized.

So mandating cloning and serialization in all implementations is certainly much less bendy and greater restrictive. The particular implementation ought to make the decision as to whether it can be cloned or serialized.

Q10. What is a diamond operator?

Ans: Diamond operator permit the compiler infer the type arguments for the time-honored training. It is introduced in Java 7.

As Example - Before JDK7 if we had to define a Map the usage of String as both Key and Value we needed to write it like this -

Map<String, String> cityMap = new HashMap<String, String>();

In Java SE 7, you may substitute the parameterized sort of the constructor with an empty set of kind parameters (<>) called diamond operator

Map<String, String> cityMap = new HashMap<>();

Q11. Why Map interface doesn’t increase Collection interface?

Ans: Although Map interface and it’s implementations are part of Collections Framework, Map aren't collections and collections are not Map. Hence it doesn’t make sense for Map to extend Collection or vice versa.

If Map extends Collection interface, then wherein are the elements? Map consists of key-cost pairs and it presents methods to retrieve listing of Keys or values as Collection but it doesn’t suit into the “organization of factors” paradigm.

Q12. What are the modifications in Collections framework in Java 8?

There are several adjustments in Collections Framework in Java 8 broadly speaking stimulated through the inclusion of Lambda expression in Java eight -
 

Stream API- Stream can be received for Collection thru the movement() and parallelStream() techniques;

As exp when you have a listing of towns in a List and also you want to remove the replica towns from that list it may be accomplished as cityList = cityList.Movement().Wonderful().Collect(Collectors.ToList());

ForEach loopwhich can be used with Collection. Spliterators which can be helpful in parallel processing where numerous threads can itearate/process part of the gathering.

New methods are delivered to Collections like replaceAll, getOrDefault, putIfAbsent in Map.

HashMap, LinkedHashMapand ConcurrentHashMap.Implementation is changed to reduce hash collisions. Instead of linked listing a balanced tree is used to save the entries after a certain threshold is reached.

Q13. What is fail-rapid property?

Ans: At excessive degree - Fail-speedy is a property of a device or software program with admire to

its response to screw ups. A fail-rapid system is designed to without delay record any failure or situation this is probably to result in failure. Fail-speedy structures are

typically designed to prevent regular operation rather than try and preserve a probable-mistaken manner.

When a trouble happens, a fail-speedy gadget fails immediately and visibly. Failing fast is a non-intuitive technique: "failing right now and visibly" appears like it would make your software program more fragile, but it actually makes it extra strong. Bugs are less complicated to find and connect, so fewer move into manufacturing.

In Java, Fail-fast time period may be related to context of iterators. If an iterator has been created on a collection object and a few different thread tries to regulate the gathering item "structurally", a concurrent amendment exception may be thrown.

It is viable for other threads although to invoke "set" approach because it doesn't modify the collection "structurally". However, if previous to calling "set", the gathering has been modified structurally, "IllegalArgumentException" might be thrown. 

Q14. What is an Iterator?

Ans: Iterator interface presents strategies to iterate over any Collection. We can get iterator instance from a Collection the usage of iterator method. Iterator takes the location of Enumeration within the Java Collections Framework. Iterators permit the caller to put off factors from the underlying collection in the course of the new release.

Q15. What is ForEach announcement added in Java eight?

Ans: Java eight has brought a purposeful style lopping to the Collections. Real benefit of this loop is whilst it's miles used on a movement with the chain of useful techniques. If you have a Map<String, String> then it can be looped the use of ForEach announcement like this -

Set<Map.Entry<String, String>> valueSet = cityMap.EntrySet();

valueSet.ForEach((a)->System.Out.Println("Key is " + a.GetKey() + " Value is " + a.GetValue()));

Q16. What is difference among Enumeration and Iterator interface?

Ans: Enumeration is twice as fast as Iterator and makes use of very much less reminiscence. Enumeration is very basic and suits to primary wishes. But Iterator is plenty more secure compared to Enumeration as it usually denies different threads to regulate the gathering item which is being iterated through it.

Iterator takes the place of Enumeration in the Java Collections Framework. Iterators permit the caller to eliminate factors from the underlying series that isn't viable with Enumeration. Iterator method names have been progressed to make it’s capability clear.

Q17. What is RandomAccess interface?

Ans: RandomAccess interface is a marker interface utilized by List implementations to indicate that they guide speedy (typically consistent time) random get right of entry to.

Note that the use of it with a sequential get right of entry to listing like LinkedList will bring about taking greater time to get admission to a particular element.

Q18. Why there isn't approach like Iterator.Add() to add factors to the gathering?

Ans: The semantics are doubtful, given that the contract for Iterator makes no guarantees about the order of new release. Note, but, that ListIterator does provide an add operation, as it does guarantee the order of the new release.

Q19. Which collection classes put into effect random get entry to interface?

Ans: In Java.Util bundle the training that enforce random get entry to interface are - ArrayList, CopyOnWriteArrayList, Stack, Vector.

Q20.  How can we make Hashmap synchronized?

Ans: HashMap may be synchronized by using Map m = Collections.SynchronizedMap(hashMap);

Q21. Why Iterator don’t have a way to get subsequent detail immediately with out shifting the cursor?

Ans: It can be implemented on top of modern-day Iterator interface however because it’s use may be uncommon, it doesn’t make sense to include it in the interface that everybody has to put into effect.

Q22. What is the difference between Collection and Collections?

Ans: Collection is an interface which is the basis of the Collections framework, as you could see in query#2, List, Set and Queue are the interfaces that amplify the Collection interface.

Collections is a utility class with static methods that function on or return Collections. It affords numerous techniques like type, opposite, synchronizedCollection, binarySearch and so forth.

Q23. What is unique between Iterator and ListIterator?

Ans:We can use Iterator to traverse Set and List collections whereas ListIterator may be used with Lists simplest. Iterator can traverse in ahead direction best while ListIterator may be used to traverse in both the instructions.

ListIterator inherits from Iterator interface and springs with more functionalities like including an element, changing an element, getting index function for preceding and next factors.

Q24. What all Collection training are inherently thread-secure?

Ans: In the initial Collection training like Vector, HashTable and Stack all the techniques were synchronized to make these instructions thread secure.

Later implementations beginning from Java 1.2 were not synchronized.

Classes in java.Util.Concurrent bundle like ConcurrentHashMap, CopyOnWriteArrayList also offers thread safety but with a unique implementation that doesn't require making all of the techniques synchronized.

Q25. What are different methods to iterate over a list?

Ans: We can iterate over a list in  extraordinary approaches – the use of iterator and using for-each loop.

List<String> strList = new ArrayList<>();

//using for-each loop

for(String obj : strList)

System.Out.Println(obj);

//using iterator

Iterator<String> it = strList.Iterator();

while(it.HasNext())

String obj = it.Subsequent();

System.Out.Println(obj);

Using iterator is extra thread-safe as it makes positive that if underlying listing factors are modified, it's going to throw ConcurrentModificationException.

Q26. How can we synchronize a collection OR how to make a set thread-safe?

Ans: Collections elegance has several static techniques that go back synchronized collections. Each of the six middle collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap - has one static manufacturing facility method.

Public static <T> Collection<T> synchronizedCollection(Collection<T> c);

public static <T> Set<T> synchronizedSet(Set<T> s);

public static <T> List<T> synchronizedList(List<T> listing);

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m);

public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s);

public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m);

Each of those strategies returns a synchronized (thread-safe) Collection backed up through the desired series.

Q27. Where will you use Vector and in which will you operate ArrayList?

Ans: The primary difference among a Vector and an ArrayList is that, vector is synchronized while ArrayList isn't. Thus on every occasion there's a possibility of a couple of threads getting access to the identical example, one have to use Vector. While if not a couple of threads are going to get admission to the identical example then use ArrayList. Non synchronized statistics shape will give higher overall performance than the synchronized one.

Q28. What do you understand by using iterator fail-fast belongings?

Ans: Iterator fail-speedy assets checks for any change inside the structure of the underlying collection everytime we attempt to get the following detail. If there are any adjustments observed, it throws ConcurrentModificationException. All the implementations of Iterator in Collection lessons are fail-rapid via design besides the concurrent series instructions like ConcurrentHashMap and CopyOnWriteArrayList.

Q29. How to make a Collection Class immutable?

Ans: Collections magnificence affords static approach to make a Collection unmodifiable. Each of the six center collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap - has one static factory technique.

Public static <T> Collection<T> unmodifiableCollection(Collection<? Extends T> c);public static <T> Set<T> unmodifiableSet(Set<? Extends T> s);public static <T> List<T> unmodifiableList(List<? Extends T> list);public static <K,V> Map<K, V> unmodifiableMap(Map<? Extends K, ? Extends V> m);public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<? Extends T> s);public static <K,V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? Extends V> m);

Q30. What is distinction among fail-fast and fail-secure?

Ans: Iterator fail-secure belongings paintings with the just like underlying collection, for this reason it’s no longer affected by any modification in the series. By design, all the collection lessons in package deal are fail-rapid whereas series instructions in are fail-safe. Fail-speedy iterators throw ConcurrentModificationException while fail-safe iterator in no way throws ConcurrentModificationException.

Q31. How ArrayList works internally in Java?

Ans: Basic records shape utilized by ArrayList to save objects is an array of Object elegance, that is defined like -

temporary Object[] elementData;

When we upload an detail to an ArrayList it first verifies whether or not it has that tons capability inside the array to keep new element or no longer, in case there isn't then the new potential is calculated which is 50% more than the vintage potential and the array is accelerated by that a great deal capability (Actually makes use of Arrays.CopyOf which returns the authentic array increased to the brand new period)

Q32. How to avoid ConcurrentModificationException while iterating a set?

Ans: We can use concurrent collection classes to avoid even as iterating over a group, as an instance CopyOnWriteArrayList rather than ArrayList.Check this publish for ConcurrentHashMap Example.

Q33. How to add factors to an ArrayList?

Ans:

List affords a method add(E e)which appends specific detail to the end of the listing. Using add(E e) method will mean hold adding elements sequentially to the listing.

Another add approach - upload(int index, E detail)inserts the specified element at the required role in this listing.

Third approach addAll(int index, Collection<? Extends E> c)inserts all the elements in the specified collection into this list, beginning at the desired function.

Q34. Why there aren't any concrete implementations of Iterator interface?

Ans: Iterator interface declare methods for iterating a set but it’s implementation is obligation of the Collection implementation training. Every series elegance that returns an iterator for traversing has it’s very own Iterator implementation nested magnificence.

This lets in series instructions to chose whether iterator is fail-speedy or fail-secure. For instance ArrayList iterator is fail-fast whereas CopyOnWriteArrayList iterator is fail-safe.

Q35. Does ArrayList allow replica factors?

Ans: Yes. List permits replica elements to be introduced.

Q36. What is Unsupported Operation Exception?

Ans: Unsupported Operation Exception is the exception used to signify that the operation is not supported. It’s used significantly in JDK lessons, in collections framework throws this exception for all and operations.

Q37. Does ArrayList allow null?

Ans: In ArrayList any number of nulls may be delivered.

Q38. What is the difference among Sorting overall performance of Arrays.Type() vs Collections.Sort() ? Which one is faster? Which one to apply and whilst?

Ans: Many developers are involved about the overall performance difference among java.Util.Array.Sort() java.Util.Collections.Kind() methods. Both methods have equal algorithm the best distinction is type of input to them. Collections.Sort() has a input as List so it does a translation of List to array and vice versa that's a further step while sorting.

So this must be used whilst you are attempting to sort a list. Arrays.Type is for arrays so the sorting is carried out immediately at the array. So simply it have to be used if you have a array to be had with you and also you want to sort it.




CFG