YouTube Icon

Interview Questions.

Top 50 Java Collections Framework Interview Questions - Jul 26, 2022

fluid

Top 50 Java Collections Framework Interview Questions

Q1. How To Avoid Concurrentmodificationexception While Iterating A Collection?

You need to first try to discover some other opportunity iterator which are fail-safe. For example if you are the use of List and you can use ListIterator. If it's miles legacy collection, you may use enumeration.

If above alternatives are not possible then you could use one of 3 modifications:

If you're using JDK1.Five or better then you may use ConcurrentHashMap and CopyOnWriteArrayList lessons. It is the encouraged method.

You can convert the list to an array and then iterate on the array.

You can lock the list while iterating by means of putting it in a synchronized block.

Please word that remaining two processes will reason a overall performance hit.

Q2. What Is The Advantage Of Generic Collection?

If we use customary magnificence, we don't want typecasting. It is typesafe and checked at assemble time.

Q3. What Is The Difference Between Hashmap And Treemap?

HashMap keeps no order but TreeMap continues ascending order.

Q4. Difference Between Iterator And Listiterator?

There are 3 Differences are there:

We can use Iterator to traverse Set and List and additionally Map kind of Objects. But List Iterator can be used to traverse for List kind Objects, but not for Set form of Objects.

By using Iterator we are able to retrieve the elements from Collection Object in ahead course only whereas List Iterator, which allows you to traverse in either instructions the usage of hasPrevious() and former() methods.

ListIterator lets in you alter the list using upload() cast off() methods. Using Iterator you cannot upload, only get rid of the elements.

Q5. How To Reverse The List?

This question is just like above to test your understanding of Collections software class. Use it opposite() approach to opposite the listing.

Collections.Reverse(list);

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

It models the mathematical set in set idea. Set interface is like List interface but with some differences. First, it isn't always ordered collection.So no ordering is preserved while adding or disposing of elements. The primary function it does offer is “distinctiveness of elements“. It does now not guide duplicate elements.

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

Based on above motives, it does not have operations based on indexes of elements like List. It simplest has strategies which might be inherited by means of Collection interface.

Main training enforcing Set interface are : EnumSet, HashSet, LinkedHashSet, TreeSet.

Q7. What Is The Difference Between Collection And Collections?

Collection is an interface whereas Collections is a category. Collection interface affords everyday functionality of information structure to List, Set and Queue. But, Collections class is to kind and synchronize series elements.

Q8. What Are Collections And Arrays Classes?

Collections and Arrays training are special utility lessons to help collection framework center training. They provide utility functions to get read-simplest/ synchronized collections, kind the gathering on numerous approaches and many others.

Arrays also allows array of items to convert in collection objects. Arrays also have some features which helps in copying or operating in part of array gadgets.

Q9. Difference Between Iterator And Enumeration?

Iterators range from enumerations in 3 methods:

Iterators allow the caller to remove elements from the underlying collection all through the generation with its take away() technique. You cannot add/eliminate factors from a set while the use of enumerator.

Enumeration is to be had in legacy lessons i.E Vector/Stack and many others. While Iterator is available in all modern series instructions.

Another minor distinction is that Iterator has improved method names e.G. Enumeration.HasMoreElement() has grow to be Iterator.HasNext(), Enumeration.NextElement() has turn out to be Iterator.Subsequent() and so forth.

Q10. Difference Between Hashmap And Hashtable?

There are several differences between HashMap and Hashtable in Java:

Hashtable is synchronized, while HashMap is not.

Hashtable does not allow null keys or values. HashMap lets in one null key and any quantity of null values.

The 1/3 great difference among HashMap vs Hashtable is that Iterator inside the HashMap is a fail-rapid iterator at the same time as the enumerator for the Hashtable is not.

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

The sole motive of an Iterator is to enumerate via a group. All collections include the add() approach to serve your purpose. There might be no point in adding to an Iterator due to the fact the gathering might also or won't be ordered. And add() technique can't have identical implementation for ordered and unordered collections.

Q12. What Is Difference Between Fail-speedy And Fail-secure?

You have understood fail-rapid in preceding question. Fail-safe iterators are just contrary to fail-rapid. They by no means fail if you regulate the underlying collection on which they're iterating, due to the fact they work on a twin of Collection rather than unique series and that’s why they're known as as fail-safe iterator. Iterator of CopyOnWriteArrayList is an instance of fail-safe Iterator also iterator written through ConcurrentHashMap keySet is also fail-safe iterator and by no means throw ConcurrentModificationException.

Q13. Why Collection Interface Does Not Extend Cloneable And Serializable Interface?

Well, most effective wer is “there's no want to do it“. Extending an interface clearly me that you are growing a subtype of interface, in different words a more specialized conduct and Collection interface is not anticipated to do what Cloneable and Serializable interfaces do.

Another motive is that now not each person could have a cause to have Cloneable collection due to the fact if it has very huge facts, then every unnecessary clone operation will eat a huge reminiscence. Beginners might use it without understanding the results.

Another cause is that Cloneable and Serializable are very specialized behavior and so should be implemented best when required. For example, many concrete classes in series put into effect these interfaces. So in case you need this option. Use these collection classes in any other case use their opportunity lessons.

Q14. How To Synchronize List, Set And Map Elements?

Yes, Collections elegance affords methods to make List, Set or Map factors as synchronized:

public static List synchronizedList(List l)

public static Set synchronizedSet(Set s)

public static SortedSet synchronizedSortedSet(SortedSet s)

public static Map synchronizedMap(Map m)

public static SortedMap synchronizedSortedMap(SortedMap m)

Q15. What Is The Difference Between List And Set?

List can include reproduction elements while Set carries best precise factors.

Q16. What Is Comparable And Comparator Interface?

In java. All collection which have function of automated sorting, uses compare techniques to make sure an appropriate sorting of elements. For example lessons which use sorting are TreeSet, TreeMap and many others.

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

Comparable facilitates in preserving default herbal sorting, while Comparator facilitates in sorting the factors in a few unique required sorting pattern. The instance of comparator if surpassed generally as series’s constructor argument in helping collections.

Q17. What Is The Difference Between Iterator And Listiterator?

Iterator traverses the factors in ahead direction simplest while ListIterator traverses the factors in ahead and backward direction.

Iterator:

Iterator traverses the elements in ahead path handiest.

Iterator can be utilized in List, Set and Queue.

ListIterator:

ListIterator traverses the elements in back and forth directions each.

ListIterator can be utilized in List handiest.

Q18. What Is The Difference Between Arraylist And Vector?

ArrayList:

ArrayList is not synchronized.

ArrayList isn't a legacy class.

ArrayList will increase its length via 50% of the array length.

Vector:

Vector is synchronized.

Vector is a legacy magnificence.

Vector will increase its length by way of doubling the array length.

Q19. What Are Different Collection Views Provided By Map Interface?

Map interface provides three perspectives of key-values pairs stored in it:

key set view

price set view

access set view

All the views may be navigated using iterators.

Q20. Difference Between Arraylist And Linkedlist?

LinkedList keep factors inside a doubly-connected list facts structure. ArrayList store factors within a dynamically resizing array.

LinkedList lets in for consistent-time insertions or removals, but handiest sequential get admission to of elements. In other words, you can stroll the list forwards or backwards, however grabbing an element inside the middle takes time proportional to the size of the list. ArrayLists, then again, permit random get entry to, so you can grasp any element in regular time. But including or eliminating from everywhere but the give up calls for transferring all the latter factors over, both to make an opening or fill the distance.

LinkedList has extra reminiscence overhead than ArrayList because in ArrayList each index best holds real object (statistics) but in case of LinkedList every node holds both data and cope with of next and former node.

Q21. What Is Blockingqueue?

A Queue that additionally helps operations that look forward to the queue to come to be non-empty whilst retrieving an element, and anticipate space to end up to be had within the queue whilst storing an detail.

BlockingQueue techniques are available four paperwork: one throws an exception, the second one returns a special value (both null or fake, relying at the operation), the 1/3 blocks the cutting-edge thread indefinitely until the operation can be triumphant, and the fourth blocks for most effective a given most time limit before giving up.

Q22. Why Map Interface Does Not Extend Collection Interface?

A appropriate wer to this interview query is “due to the fact they may be incompatible“. Collection has a method add(Object o). Map can't have such approach because it want key-price pair. There are different reasons also which include Map helps keySet, valueSet and so on. Collection training does no longer have such views.

Due to such massive differences, Collection interface became now not used in Map interface, and it become build in separate hierarchy.

Q23. Difference Between Vector And Arraylist?

Lets word down the variations:

All the strategies of Vector is synchronized. But, the methods of ArrayList is not synchronized.

Vector is a Legacy magnificence added in first release of JDK. ArrayList became part of JDK 1.2, whilst collection framework became added in java.

By default, Vector doubles the scale of its array when it's miles re-sized internally. But, ArrayList increases by way of half of of its size whilst it is re-sized.

Q24. What Is The Difference Between Set And Map?

Set contains values handiest whereas Map consists of key and values both.

Q25. What Is The Difference Between Hashset And Treeset?

HashSet maintains no order whereas TreeSet keeps ascending order.

Q26. What Is The Dictionary Class?

The Dictionary elegance offers the capability to keep key-fee pairs.

Q27. What Is Unsupportedoperationexception?

This exception is thrown on invoked techniques which aren't supported via actual collection kind.

For instance, if you make a study-simplest list list the use of “Collections.UnmodifiableList(list)” after which call add() or cast off() technique, what should appear. It have to virtually throw UnsupportedOperationException.

Q28. How Hashset Store Elements?

You need to understand that HashMap shop key-price pairs, with one situation i.E. Keys may be specific. HashSet makes use of Map’s this selection to ensure area of expertise of elements. In HashSet elegance, a map statement is as underneath:

personal trient HashMap<E,Object> map;

//This is delivered as fee for each key

non-public static final Object PRESENT = new Object();

So when you store a detail in HashSet, it stores the detail as key in map and “PRESENT” item as cost. (See declaration above).

Public boolean upload(E e)

go back map.Placed(e, PRESENT)==null;

 

Q29. Difference Between List And Map?

Perhaps maximum clean query. List is collection of elements wherein as map is series of key-fee pairs. There is certainly plenty of variations which originate from first assertion. They have separate pinnacle stage interface, separate set of regularly occurring techniques, specific supported techniques and exceptional views of collection.

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

By definition, a set is an object that represents a collection of items. Like in set idea, a fixed is organization of elements. Easy enough !!

Prior to JDK 1.2, JDK has some software instructions which includes Vector and HashTable, however there has been no idea of Collection framework. Later from JDK 1.2 onwards, JDK felt the need of getting a regular assist for reusable information systems. Finally, the collections framework was designed and evolved by and large by using Joshua Bloch, and become delivered in JDK 1.2.

Its most significant benefits may be listed as:

Reduced programming attempt due to geared up to use code

Increased overall performance due to high-overall performance implementations of statistics systems and algorithms

Provides interoperability among unrelated APIs via setting up a common language to pass collections back and forth

Easy to learn APIs with the aid of mastering only some top degree interfaces and supported operations

Q31. Why We Override Equals() Method?

The equals approach is used to test whether  gadgets are same or no longer. It wishes to be overridden if we need to test the items based on property. For instance, Employee is a class that has 3 information members: identity, call and revenue. But, we need to check the equality of worker item on the idea of profits. Then, we need to override the equals() approach.

Q32. How To Convert An Array Of String To Arraylist?

This is greater of a programmatic query that is visible at novice stage. The cause is to test the information of applicant in Collection utility lessons. For now, we could learn that there are two application classes in Collection framework which can be normally visible in interviews i.E. Collections and Arrays.

Collections magnificence affords a few static functions to carry out specific operations on series sorts. And Arrays offer software features to be achieved on array types.

//String array

String[] phrases = "ace", "increase", "group", "dog", "eon";

//Use Arrays software class

List wordList = Arrays.AsList(words);

//Now you can iterate over the list

Please now not that this characteristic is not specific to String magnificence, it'll return List of detail of any kind, of which the array is. E.G.

//String array

Integer[] nums = 1,2,3,4;

//Use Arrays software elegance

List numsList = Arrays.AsList(nums);

Q33. Difference Between Set And List?

The most substantive variations are :

Set is unordered collection in which List is ordered collection based totally on zero based index.

List allow replica factors but Set does not permit duplicates.

List does no longer save you putting null factors (as many you like), however Set will allow only one null detail.

Q34. What Is The Difference Between Hashset And Hashmap?

HashSet incorporates handiest values while HashMap incorporates access(key,price). HashSet can be iterated but HashMap want to transform into Set to be iterated

Q35. What Is The Difference Between Arraylist And Linkedlist?

ArrayList:

ArrayList uses a dynamic array.

ArrayList is not efficient for manipulation because a whole lot of shifting is required.

ArrayList is better to store and fetch statistics.

LinkedList:

LinkedList makes use of doubly linked listing.

LinkedList is green for manipulation.

LinkedList is higher to control records.

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

The default size of load factor is 0.7@The default capability is computed as preliminary capacity * load factor. For instance, 16 * zero.75 = @So, 12 is the default ability of Map.

Q37. What Is The Difference Between Comparable And Comparator?

Comparable:

Comparable offers handiest one form of sequence.

It gives one approach named compareTo().

It is found in java.Lang bundle.

If we enforce Comparable interface, actual magnificence is changed.

Comparator:

Comparator offers a couple of form of sequences.

It offers one method named compare().

It's miles found in java.Util bundle.

Actual class isn't changed.

Q38. When To Use Hashmap Or Treemap?

HashMap is widely known class and everybody recognise that. So, I will depart this component by using pronouncing that it's miles used to keep key-price pairs and permits to carry out many operations on such collection of pairs.

TreeMap is unique form of HashMap. It keeps the ordering of keys that is lacking in HashMap magnificence. This ordering isby default “natural ordering”. The default ordering can be override by using supplying an example of Comparator elegance, whose examine method can be used to hold ordering of keys.

Please word that each one keys inserted into the map ought to implement the Comparable interface (this is important to decide the ordering). Furthermore, all such keys have to be jointly comparable: k1.CompareTo(k2) have to no longer throw a ClassCastException for any keys k1 and k2 within the map. If the person attempts to place a key into the map that violates this constraint (as an example, the user attempts to place a string key into a map whose keys are integers), the placed(Object key, Object cost) name will throw a ClassCastException

Q39. How To Make A Collection Thread Safe?

Use underneath strategies:

Collections.SynchronizedList(listing);

Collections.SynchronizedSet(set);

Collections.SynchronizedMap(map);

Above methods take collection as parameter and go back equal sort of series that are synchronized and thread secure.

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

A java listing is a “ordered” collection of factors. This ordering is a zero based index. It does not care about duplicates. Apart from techniques defined in Collection interface, it does have its own techniques additionally that are in large part to govern the gathering based on index place of detail. These strategies can be grouped as search, get, iteration and variety view. All above operations guide index places.

The predominant lessons imposing List interface are: Stack, Vector, ArrayList and LinkedList. Read more about them in java documentation.

Q41. What Is The Advantage Of Properties File?

If you change the value in houses file, you don't want to recompile the java magnificence. So, it makes the application easy to manipulate.

Q42. Difference Between Treeset And Sortedset?

SortedSet is an interface which TreeSet implements.

Q43. What Do You Understand By Iterator Fail-rapid Property?

Fail-fast Iterators fail as soon as they realized that shape of Collection has been modified considering new release has all started. Structural changes me adding, doing away with or updating any detail from series whilst one thread is Iterating over that series. Fail-rapid conduct is applied by using retaining a change matter and if generation thread realizes the exchange in modification rely it throws ConcurrentModificationException.

Q44. What Is The Difference Between Hashmap And Hashtable?

HashMap:

HashMap isn't synchronized.

HashMap can contain one null key and a couple of null values.

Hashtable:

Hashtable is synchronized.

Hashtable can't include any null key or null price.

Q45. What Is The Difference Between Iterator And Enumeration?

Iterator:

Iterator can traverse legacy and non-legacy elements.

Iterator is fail-fast.

Iterator is slower than Enumeration.

Enumeration:

Enumeration can traverse simplest legacy elements.

Enumeration isn't always fail-rapid.

Enumeration is faster than Iterator.

Q46. Difference Between Hashmap And Hashset?

HashMap is collection of key-cost pairs while HashSet is un-ordered series of specific factors. That’s it. No need to explain in addition.

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

Two special keys with the identical hash fee is known as hash-collision. Two one-of-a-kind entries may be saved in a unmarried hash bucket to keep away from the collision

Q48. What Does The Hashcode() Method?

The hashCode() approach returns a hash code cost (an integer quantity). The hashCode() approach returns the identical integer number, if  keys (through calling equals() technique) are same.

But, it's miles feasible that two hash code numbers will have one of a kind or identical keys

Q49. What Are Different Ways To Iterate Over A List?

You can iterate over a listing the use of following methods:

Iterator loop.

For loop.

For loop (Advance).

While loop.

Q50. How To Make A Collection Read Only?

Use following methods:

Collections.UnmodifiableList(list);

Collections.UnmodifiableSet(set);

Collections.UnmodifiableMap(map);

These techniques takes collection parameter and return a new read-simplest collection with same elements as in authentic series.




CFG