YouTube Icon

Interview Questions.

Top 100+ Java Collections Framework Interview Questions And Answers - May 31, 2020

fluid

Top 100+ Java Collections Framework Interview Questions And Answers

Question 1. What Is The Difference Between Arraylist And Vector?

Answer :

ArrayList:

ArrayList isn't always synchronized.
ArrayList isn't a legacy elegance.
ArrayList increases its size by 50% of the array length.
Vector:

Vector is synchronized.
Vector is a legacy class.
Vector increases its size by using doubling the array size.
Question 2. What Is The Difference Between Arraylist And Linkedlist?

Answer :

ArrayList:

ArrayList makes use of a dynamic array.
ArrayList isn't efficient for manipulation due to the fact a number of shifting is required.
ArrayList is better to store and fetch information.
LinkedList:

LinkedList uses doubly related list.
LinkedList is green for manipulation.
LinkedList is better to manipulate information.
Adv Java Interview Questions
Question three. What Is The Difference Between Iterator And Listiterator?

Answer :

Iterator traverses the factors in ahead route handiest while ListIterator traverses the factors in ahead and backward path.

Iterator:

Iterator traverses the factors in forward course best.
Iterator can be utilized in List, Set and Queue.
ListIterator:

ListIterator traverses the factors in backward and forward instructions each.
ListIterator may be utilized in List best.
Question 4. What Is The Difference Between Iterator And Enumeration?

Answer :

Iterator:

Iterator can traverse legacy and non-legacy factors.
Iterator is fail-fast.
Iterator is slower than Enumeration.
Enumeration:

Enumeration can traverse most effective legacy elements.
Enumeration isn't always fail-rapid.
Enumeration is quicker than Iterator.
Adv Java Tutorial
Question five. What Is The Difference Between List And Set?

Answer :

List can comprise reproduction elements while Set consists of handiest specific factors.

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

Answer :

HashSet keeps no order whereas TreeSet continues ascending order.

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

Answer :

Set carries values best whereas Map carries key and values both.

J2EE Tutorial Core Java Interview Questions
Question eight. What Is The Difference Between Hashset And Hashmap?

Answer :

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

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

Answer :

HashMap continues no order however TreeMap keeps ascending order.

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

Answer :

HashMap:

HashMap is not synchronized.
HashMap can include one null key and multiple null values.
Hashtable:

Hashtable is synchronized.
Hashtable can not comprise any null key or null price.
Core Java Tutorial
Question 11. What Is The Difference Between Collection And Collections?

Answer :

Collection is an interface whereas Collections is a class. Collection interface gives regular capability of information shape to List, Set and Queue. But, Collections elegance is to type and synchronize series factors.

Java-Springs Interview Questions
Question 12. What Is The Difference Between Comparable And Comparator?

Answer :

Comparable:

Comparable offers handiest one type of collection.
It presents one approach named compareTo().
It is located in java.Lang bundle.
If we put in force Comparable interface, real class is modified.
Comparator:

Comparator presents more than one form of sequences.
It provides one approach named examine().
It is found in java.Util package.
Actual magnificence isn't modified.
Adv Java Interview Questions
Question thirteen. What Is The Advantage Of Properties File?

Answer :

If you exchange the value in properties report, you do not want to recompile the java elegance. So, it makes the utility clean to control.

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

Answer :

The hashCode() technique returns a hash code fee (an integer variety). The hashCode() method returns the same integer wide variety, if two keys (through calling equals() technique) are identical.

But, it's far possible that  hash code numbers can have exceptional or equal keys

Question 15. Why We Override Equals() Method?

Answer :

The equals approach is used to test whether two gadgets are same or not. It desires to be overridden if we want to check the objects based on property. For instance, Employee is a class that has 3 data contributors: identification, name and salary. But, we need to check the equality of employee item on the basis of profits. Then, we want to override the equals() approach.

JMS(Java Message Service) Interview Questions
Question 16. How To Synchronize List, Set And Map Elements?

Answer :

Yes, Collections class affords techniques 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)
Java-Springs Tutorial
Question 17. What Is The Advantage Of Generic Collection?

Answer :

If we use regular elegance, we do not need typecasting. It is typesafe and checked at assemble time.

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

Answer :

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

J2EE Interview Questions
Question 19. What Is The Dictionary Class?

Answer :

The Dictionary class affords the capability to shop key-value pairs.

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

Answer :

The default size of load aspect is zero.Seventy five. The default ability is computed as initial ability * load element. For example, 16 * zero.75 = 12. So, 12 is the default potential of Map.

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

Answer :

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

Prior to JDK 1.2, JDK has some application classes 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 steady support for reusable records systems. Finally, the collections framework changed into designed and developed mainly with the aid of Joshua Bloch, and changed into brought in JDK 1.2.

Its maximum great blessings may be listed as:

Reduced programming attempt because of ready to apply code
Increased performance due to excessive-overall performance implementations of information systems and algorithms
Provides interoperability between unrelated APIs by means of setting up a common language to pass collections from side to side
Easy to analyze APIs by means of studying only a few top stage interfaces and supported operations
Question 22. Why Collection Interface Does Not Extend Cloneable And Serializable Interface?

Answer :

Well, only answer is “there's no need to do it“. Extending an interface sincerely manner which you are developing a subtype of interface, in other phrases a greater specialised behavior and Collection interface isn't always expected to do what Cloneable and Serializable interfaces do.

Another cause is that now not everyone can have a cause to have Cloneable collection due to the fact if it has very large statistics, then every useless clone operation will consume a massive memory. Beginners might use it without knowing the outcomes.

Another reason is that Cloneable and Serializable are very specialized behavior and so need to be carried out best when required. For example, many concrete instructions in series put in force those interfaces. So in case you want this selection. Use these series training otherwise use their opportunity training.

Java eight Tutorial
Question 23. Why Map Interface Does Not Extend Collection Interface?

Answer :

A right solution to this interview query is “because they may be incompatible“. Collection has a technique add(Object o). Map can't have such method as it want key-price pair. There are different reasons additionally such as Map helps keySet, valueSet etc. Collection lessons does no longer have such perspectives.

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

Java eight Interview Questions
Question 24. Why We Use List Interface? What Are Main Classes Implementing List Interface?

Answer :

A java listing is a “ordered” collection of factors. This ordering is a zero based totally index. It does no longer care about duplicates. Apart from strategies defined in Collection interface, it does have its own methods additionally which can be in large part to govern the collection based on index region of element. These methods may be grouped as search, get, new release and variety view. All above operations support index places.

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

Core Java Interview Questions
Question 25. How To Convert An Array Of String To Arraylist?

Answer :

This is extra of a programmatic query that's visible at amateur stage. The rationale is to check the information of applicant in Collection software classes. For now, shall we examine that there are  application classes in Collection framework which can be in the main visible in interviews i.E. Collections and Arrays.

Collections magnificence affords a few static features to carry out particular operations on series kinds. And Arrays provide application features to be achieved on array sorts.

//String array
String[] phrases = "ace", "boom", "group", "canine", "eon";
//Use Arrays application elegance
List wordList = Arrays.AsList(phrases);
//Now you can iterate over the list
Please no longer that this feature isn't always specific to String magnificence, it'll go back List of element of any kind, of which the array is. E.G.

//String array
Integer[] nums = 1,2,3,4;
//Use Arrays application class
List numsList = Arrays.AsList(nums);

Question 26. How To Reverse The List?

Answer :

This query is similar to above to test your information of Collections software magnificence. Use it reverse() technique to opposite the listing.
Collections.Opposite(listing);

Java Programmer Interview Questions
Question 27. Why We Use Set Interface? What Are Main Classes Implementing Set Interface?

Answer :

It models the mathematical set in set idea. Set interface is like List interface but with some variations. First, it isn't ordered collection.So no ordering is preserved while adding or casting off elements. The major characteristic it does provide is “specialty of factors“. It does no longer assist reproduction elements.

Set additionally provides a more potent settlement on the conduct of the equals and hashCode operations, allowing Set times to be in comparison meaningfully even though their implementation sorts range. Two Set times are same if they contain the identical factors.

Based on above reasons, it does now not have operations primarily based on indexes of factors like List. It only has strategies that are inherited by way of Collection interface.

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

JSP Interview Questions
Question 28. How Hashset Store Elements?

Answer :

You ought to realize that HashMap store key-value pairs, with one circumstance i.E. Keys could be particular. HashSet uses Map’s this selection to make certain specialty of factors. In HashSet magnificence, a map declaration is as below:

private transient HashMap<E,Object> map;
//This is introduced as value for each key
non-public static very last Object PRESENT = new Object();
So when you save a element in HashSet, it shops the detail as key in map and “PRESENT” object as price. (See statement above).

Public boolean add(E e)

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


Question 29. What Are Collections And Arrays Classes?

Answer :

Collections and Arrays classes are unique software instructions to aid collection framework center instructions. They offer utility functions to get examine-best/ synchronized collections, sort the gathering on numerous ways and so on.

Arrays also enables array of items to transform in collection objects. Arrays additionally have a few features which facilitates in copying or operating in part of array items.

Question 30. What Is Comparable And Comparator Interface?

Answer :

In java. All series that have characteristic of automated sorting, makes use of compare methods to make certain the precise sorting of factors. For example classes which use sorting are TreeSet, TreeMap and many others.

To sort the records factors a category needs to put into effect Comparator or Comparable interface. That’s why all Wrapper training like Integer,Double and String elegance implements Comparable interface.

Comparable helps in retaining default natural sorting, while Comparator helps in sorting the elements in a few special required sorting pattern. The instance of comparator if handed typically as series’s constructor argument in helping collections.

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

Answer :

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

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

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

Whatever the ordering used, the top of the queue is that detail which would be eliminated with the aid of a name to remove() or poll(). Also observe that Stack and Vector are each synchronized.

Usage: Use a queue if you want to system a move of incoming items in the order that they may be acquired.Good for paintings lists and managing requests.

Use a stack in case you need to push and pop from the top of the stack most effective. Good for recursive algorithms.

Question 32. What Is Blockingqueue?

Answer :

A Queue that additionally supports operations that look forward to the queue to come to be non-empty when retrieving an detail, and anticipate space to emerge as available inside the queue whilst storing an detail.

BlockingQueue strategies come in 4 paperwork: one throws an exception, the second returns a unique price (both null or fake, relying on the operation), the third blocks the cutting-edge thread indefinitely until the operation can succeed, and the fourth blocks for simplest a given maximum time restrict earlier than giving up.

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

Answer :

ArrayList, HashMap, TreeMap, Hashtable lessons provide random get right of entry to to it’s elements.

Java-Springs Interview Questions
Question 34. What Is Unsupportedoperationexception?

Answer :

This exception is thrown on invoked techniques which aren't supported through actual series type.

For instance, in case you make a read-only listing list using “Collections.UnmodifiableList(list)” and then name add() or do away with() approach, what must show up. It have to definitely throw UnsupportedOperationException.

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

Answer :

You have to first try to locate every other opportunity iterator which might be fail-secure. For example if you are the usage of List and you can use ListIterator. If it's far legacy collection, you could use enumeration.

If above alternatives are not viable then you could use considered one of three adjustments:

If you're the use of JDK1.Five or better then you can use ConcurrentHashMap and CopyOnWriteArrayList instructions. It is the recommended method.
You can convert the listing to an array and then iterate at the array.
You can lock the list while iterating by putting it in a synchronized block.
Please notice that remaining two procedures will reason a performance hit.

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

Answer :

You have understood fail-rapid in preceding query. Fail-secure iterators are just opposite to fail-rapid. They by no means fail if you alter the underlying collection on which they are iterating, due to the fact they paintings on a dead ringer for Collection instead of unique collection and that’s why they may be known as as fail-safe iterator. Iterator of CopyOnWriteArrayList is an example of fail-secure Iterator additionally iterator written through ConcurrentHashMap keySet is likewise fail-safe iterator and in no way throw ConcurrentModificationException.

JMS(Java Message Service) Interview Questions
Question 37. What Do You Understand By Iterator Fail-rapid Property?

Answer :

Fail-speedy Iterators fail as quickly as they realized that structure of Collection has been modified considering the fact that generation has all started. Structural changes manner adding, putting off or updating any detail from series even as one thread is Iterating over that collection. Fail-rapid behavior is carried out by using keeping a change remember and if new release thread realizes the alternate in modification rely it throws ConcurrentModificationException.

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

Answer :

You can iterate over a list the use of following approaches:

Iterator loop.
For loop.
For loop (Advance).
While loop.
Question 39. Why There Is Not Method Like Iterator.Add() To Add Elements To The Collection?

Answer :

The sole motive of an Iterator is to enumerate thru a group. All collections comprise the add() technique to serve your motive. There would be no point in adding to an Iterator due to the fact the gathering may or may not be ordered. And upload() technique can not have equal implementation for ordered and unordered collections.

Question 40. How To Make A Collection Thread Safe?

Answer :

Use under techniques:

Collections.SynchronizedList(listing);
Collections.SynchronizedSet(set);
Collections.SynchronizedMap(map);
Above strategies take collection as parameter and go back identical form of series which can be synchronized and thread safe.

Java applet Interview Questions
Question forty one. How To Make A Collection Read Only?

Answer :

Use following strategies:

Collections.UnmodifiableList(listing);
Collections.UnmodifiableSet(set);
Collections.UnmodifiableMap(map);
These techniques takes collection parameter and return a brand new read-best series with identical elements as in original collection.

Question forty two. Difference Between Arraylist And Linkedlist?

Answer :

LinkedList keep elements inside a doubly-linked listing facts shape. ArrayList shop elements within a dynamically resizing array.
LinkedList lets in for constant-time insertions or removals, but handiest sequential get entry to of elements. In different phrases, you may stroll the list forwards or backwards, but grabbing an detail inside the center takes time proportional to the scale of the list. ArrayLists, then again, permit random access, so you can grasp any element in steady time. But adding or removing from everywhere but the cease calls for shifting all the latter elements over, either to make an opening or fill the space.
LinkedList has greater reminiscence overhead than ArrayList because in ArrayList every index best holds actual object (facts) but in case of LinkedList each node holds each data and address of subsequent and former node.
Java Interview Questions
Question 43. Difference Between Treeset And Sortedset?

Answer :

SortedSet is an interface which TreeSet implements.

Question 44. Difference Between Iterator And Listiterator?

Answer :

There are three Differences are there:

We can use Iterator to traverse Set and List and also Map form of Objects. But List Iterator can be used to traverse for List type Objects, but no longer for Set form of Objects.
By using Iterator we can retrieve the elements from Collection Object in ahead course most effective whereas List Iterator, which lets in you to traverse in both instructions using hasPrevious() and former() methods.
ListIterator permits you modify the list using upload() cast off() methods. Using Iterator you can not upload, best do away with the elements.
Question forty five. Difference Between Hashmap And Hashset?

Answer :

HashMap is series of key-value pairs while HashSet is un-ordered series of particular elements. That’s it. No want to explain in addition.

Question forty six. Difference Between Iterator And Enumeration?

Answer :

Iterators vary from enumerations in 3 ways:

Iterators permit the caller to do away with elements from the underlying series at some stage in the generation with its cast off() method. You can not add/dispose of factors from a group when using enumerator.
Enumeration is available in legacy instructions i.E Vector/Stack and many others. While Iterator is to be had in all modern series training.
Another minor difference is that Iterator has stepped forward approach names e.G. Enumeration.HasMoreElement() has grow to be Iterator.HasNext(), Enumeration.NextElement() has come to be Iterator.Subsequent() and so forth.
Question 47. Difference Between Vector And Arraylist?

Answer :

Lets observe down the variations:

All the techniques of Vector is synchronized. But, the techniques of ArrayList isn't synchronized.
Vector is a Legacy magnificence introduced in first release of JDK. ArrayList was a part of JDK 1.2, while collection framework was brought in java.
By default, Vector doubles the dimensions of its array whilst it is re-sized internally. But, ArrayList increases via half of its length whilst it's miles re-sized.
Question 48. Difference Between Hashmap And Hashtable?

Answer :

There are numerous differences among HashMap and Hashtable in Java:

Hashtable is synchronized, whereas HashMap isn't.
Hashtable does now not permit null keys or values. HashMap lets in one null key and any variety of null values.
The 1/3 great distinction among HashMap vs Hashtable is that Iterator inside the HashMap is a fail-fast iterator whilst the enumerator for the Hashtable isn't.
Question forty nine. Difference Between List And Map?

Answer :

Perhaps maximum easy question. List is series of factors where as map is series of key-fee pairs. There is absolutely masses of variations which originate from first announcement. They have separate top stage interface, separate set of normal strategies, exceptional supported methods and special perspectives of collection.

Question 50. Difference Between Set And List?

Answer :

The maximum considerable variations are :

Set is unordered series wherein List is ordered series based on zero based index.
List permit duplicate elements however Set does no longer permit duplicates.
List does now not prevent placing null factors (as many you like), however Set will allow simplest one null detail.
Question 51. When To Use Hashmap Or Treemap?

Answer :

HashMap is widely recognized class and everybody recognise that. So, I will go away this part with the aid of announcing that it's far used to keep key-fee pairs and permits to carry out many operations on such collection of pairs.

TreeMap is unique form of HashMap. It continues the ordering of keys that's missing in HashMap elegance. This ordering isby default “herbal ordering”. The default ordering may be override by way of presenting an example of Comparator class, whose examine method could be used to hold ordering of keys.

Please word that all keys inserted into the map need to put in force the Comparable interface (this is necessary to decide the ordering). Furthermore, all such keys need to be jointly comparable: k1.CompareTo(k2) have to no longer throw a ClassCastException for any keys k1 and k2 in the map. If the consumer tries to put a key into the map that violates this constraint (as an instance, the person tries to put a string key into a map whose keys are integers), the put(Object key, Object fee) name will throw a ClassCastException

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

Answer :

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

key set view
value set view
entry set view
All the views can be navigated the use of iterators.




CFG