YouTube Icon

Interview Questions.

Top 50 Java Collections Interview Questions - Jul 26, 2022

fluid

Top 50 Java Collections Interview Questions

Q1. How To Sort Arraylist Of Strings In Descending Order?

Collections.Type() method will type the ArrayList of String in ascending order. 

To have a descending order both comparator must be provided or reverseOrder technique of the Collections class may be used.

Collections.Sort(cityList, Collections.ReverseOrder());

Q2. Which Set Implementation Should Be Used If You Want The Insertion Order To Be Maintained?

LinkedHashSet need to be used in this situation.

Q3. Difference Between Hashmap And Hashtable In Java?

Though each HashTable and HashMap shop elements as a (key, value) pair and use hashing approach to keep elements, furthermore from Java v1.2, HashTable class become retrofitted to put into effect the Map interface, making it a member of the Java Collections Framework. But there are certain distinction among the two -

HashMap isn't synchronized wherein as HashTable is synchronized.

HashMap lets in one null cost as a key and any variety of null values wherein as HashTable does no longer allow null values either as key or as value.

For traversing a HashMap an iterator can be used. For traversing a HashTable both an iterator or Enumerator may be used. The iterator used for each HashMap and HashTable is fail-speedy however the enumerator used with HashTable is fail-safe.

Performance wise HashMap is faster than the HashTable cause being HashMap isn't always synchronized.

Q4. How Arraylist Works Internally In Java?

Basic data shape used by ArrayList to store items is an array of Object class, that is described like -

trient Object[] elementData; 

When we add an detail to an ArrayList it first verifies whether it has that lots capability within the array to save new detail or now not, in case there is not then the brand new capability is calculated that is 50% extra than the vintage potential and the array is elevated through that an awful lot capability (Actually makes use of Arrays.CopyOf which returns the unique array increased to the new length)

Q5. What Is Linkedlist Class In Java? How Is It Implemented?

LinkedList elegance in Java implements List and Deque interfaces and LinkedList implements it the usage of doubly linkedlist.

Within the LinkedList implementation there may be a non-public elegance Node which provides the shape for a node in a doubly linked list. It has item variable for containing the value and two reference to Node elegance itself for connecting to subsequent and former nodes.

Q6. What Is Java Collections Framework? What Are The Benefits Of Using Collections Framework?

Java Collections Framework provides a wellknown manner to address a group of gadgets. Benefits of the Collections Framework are -

High overall performance, implementation of the Collection training (ArrayList, LinkedList, HashSet etc.) are very green and used as-is in maximum of the cases.

Reduced effort as framework already offers several implementations for maximum of the situations that can be used as-is.

Provides interoperability, as exp. In case you are the use of List interface any implementation that implements List interface can be swapped with the existing one.

If you want to extend any collection that can be easily finished using the usual interfaces furnished with inside the Collections frameworks.

Q7. Which Collection Classes Implement List Interface?

Some of the Collection lessons that implement List interface are ArrayList, CopyOnWriteArrayList, LinkedList, Stack, Vector.

Q8. How To Add Elements To An Arraylist?

List affords a method upload(E e) which appends special detail to the quit of the list. Using upload(E e) technique will suggest preserve adding factors sequentially to the list.

Another add technique - add(int index, E element) inserts the required detail at the desired role on this listing.

Third method addAll(int index, Collection<? Extends E> c) inserts all the elements in the special collection into this listing, starting at the desired function.

Q9. What Is For-every Style Loop?

Another feature which was delivered to Collection with JDK five is for-each style loop. Any collection which desires to be the target of the "for-every loop" statement has to put into effect iterable interface.

Using for-each loop is easier than constructing the iterator to iterate over the gathering and can be utilized in maximum of the instances as opposed to the use of the iterator loop.

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

For(String metropolis : cityList)

    System.Out.Println("Name " + metropolis);

 

Q10. Describe The Collection Framework Hierarchy?

At the foundation of the Collections framework is Collection interface, it have to be carried out by any magnificence that defines a set. This interface proclaims the center methods that every collection can have, if any magnificence doesn't implement any of the method then it may throw UnsupportedOperationException.

Then there are List and Set interfaces that make bigger Collection interface and furnished some of its very own behaviour in an effort to be in addition carried out by way of the training that implement List and Set interfaces respectively. 

There is likewise a Queue interface that extends collection to offer behaviour of a queue. On the opposite hand there may be Map interface which gives center methods for the Map implementations.

Q11. Why Iterator Doesn't Have Add Method Whereas Listiterator Has Add Method?

Iterator can be acquired on any Collection elegance like List or Set so settlement for Iterator makes no guarantees about the order of new release. 

But ListIterator can most effective be used to traverse a List so it does guarantee the order of the iteration. That is why ListIterator provides an add operation.

Q12. What Is Listiterator In Java?

ListIterator presents the functionality to iterate a list in both instructions. The interesting factor approximately list iterator is that it has no present day element. Its contemporary cursor position always lies among the element that could be returned by using a call to previous() and the detail that might be returned through a name to next().

Q13. What Is Hash-collision In Hash Based Collections?

In HashMap, the usage of the key, a Hash is calculated and that hash fee decides in which bucket the particular Map.Entry item will are living.

Hash collision me more than one key having the equal calculated hash fee consequently stored in the identical bucket. In HashMap, in that case Entry items are stored as a linked-listing with within the equal bucket.

Q14. When Do We Need To Override Hashcode() And Equals() Methods?

The default implementation of equals() method inside the Object magnificence is a simple reference equality take a look at.

Public boolean equals(Object obj)

     go back (this == obj);

 

The default implementation of hashCode() inside the Object magnificence simply returns integer fee of the memory cope with of the object.

It turns into very vital to override these two strategies in case we are using a custom object as key in a hash based totally collection. 

In that case we can not rely on the default implementation supplied with the aid of the Object magnificence and need to offer custom implementation of hashCode() and equals() technique.

If  gadgets Obj1 and Obj2 are same in line with their equals() approach then they ought to have the equal hash code too. Though the vice-versa isn't always true this is if  objects have the same hash code then they do no longer need to be equal too.

Q15. Difference Between Arraylist And Linkedlist In Java?

In Java collections framework ArrayList and LinkedList are  distinct implementations of List interface 

LinkedList is carried out using a doubly connected list concept where as ArrayList internally makes use of an array of Objects which can be resized dynamically

For LinkedList add(e Element) is usually O(1) in which as for ArrayList upload(e Element) operation runs in amortized consistent time, this is, adding n elements calls for O(n) time.

For LinkedList get(int index) is O(n) where as for ArrayList get(int index) is O(1).

If you are getting rid of the use of the take away(int index) method then for LinkedList elegance it will likely be O(n). In case of ArrayList getting to that index is speedy however casting off will mean shuffling the final elements to fill the distance created by the eliminated detail with within the underlying array.

Q16. How Generics Changed The Collection Framework?

With JDK5 the Collection framework was reengineered to feature generics. That was achieved to feature "Type Safety" to the collections. Prior to JDK5 (and generics) factors were stored in collections as Object references, which delivered the threat of by accident storing incompatible sorts in Collection due to the fact for Collections the entirety changed into Object reference. Which would have resulted in run time error while seeking to retrieve factors and casting them to the favored type. 

With the advent of generics now we are able to explicitly tell which records kind is to be saved in the collections, which helps in averting the run time mistakes. As Collection will throw mistakes at compile time itself for incompatible records type. As exp.

Map<String, String> cityTemperatureMap = new LinkedHashMap<String, String>();

Here we're explicitly stating that this LinkedHashMap can handiest shop string as each key and price.

Q17. What Is A Weakhashmap?

WeakHashMap is a Hash desk based totally implementation of the Map interface, with vulnerable keys. An access in a WeakHashMap will robotically be eliminated when its secret is now not in ordinary use. Which me storing simplest susceptible references permits garbage collector to do away with the entry (key-fee pair) from the map when its key is not referenced outdoor of the WeakHashMap.

In WeakHashMap each null values and the null key are supported. A WeakHashMap is created as- 

Map weakHashMap = new WeakHashMap();

Q18. Difference Between Iterator And Listiterator?

Iterator can be received on any Collection magnificence like List or Set. But ListIterator can only be used to traverse a List.

Iterator only moves in a single route the usage of next() method. ListIterator can iterate in each guidelines the use of subsequent() and former() techniques.

Iterator constantly start at the beginning of the collection.

ListIterator can be received at any point.

As Exp. If you have a List of integers numberList, you may reap a ListIterator from the 1/3 index of this List.

ListIterator<Integer> ltr = numberList.ListIterator(three);

ListIterator offers an add(E e) approach which isn't there in Iterator. Add(E e) inserts the desired element into the listing.

ListItearator additionally affords set method. Void set(E e) replaces the ultimate element lower back via next() or previous() with the required element

Q19. What Is A Diamond Operator?

Diamond operator let the compiler infer the sort arguments for the popular lessons. It is delivered in Java 7. 

As Example - Before JDK7 if we had to outline a Map the use 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 can alternative the parameterized kind of the constructor with an empty set of kind parameters (<>) referred to as diamond operator.

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

Q20. How To Join Two Or More Arraylists?

List affords a way addAll to sign up for  or more lists in Java. 

If you have one list cityList and another List secondCityList then you can be part of them the usage of addAll like this - 

cityList.AddAll(secondCityList);

Q21. Does Arraylist Allow Null?

In ArrayList any wide variety of nulls may be introduced.

Q22. How To Make A Collection Class Immutable?

Collections elegance offers static technique to make a Collection unmodifiable. Each of the six middle collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap - has one static manufacturing unit method.

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> listing);

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);

Q23. How To Remove Elements From An Arraylist?

ArrayList offers numerous techniques to take away elements from the List. Since ArrayList internally makes use of array to shop elements, one factor to be aware is that after an detail is removed from the List the remaining factors have to be shifted to fill the space created inside the underlying array.

Clear() - Removes all the factors from this list.

Cast off(int index) - Removes the detail at the desired position on this listing.

Eliminate(Object o) - Removes the first prevalence of the specified element from this listing, if it's miles gift.

RemoveAll(Collection<?> c) - Removes from this listing all of its factors that are contained in the designated collection.

RemoveIf(Predicate<? Super E> filter out) - Removes all of the elements of this series that fulfill the given predicate.

Q24. How To Remove Duplicate Elements From An Arraylist?

We can use a HashSet to do the job of disposing of the duplicate elements. HashSet simplest shops particular elements and we will use that feature of HashSet to eliminate duplicates.

If you have a List called cityList you can create a HashSet the usage of this listing - 

Set<String> citySet = new HashSet<String>(cityList);

then add this set again to the cityList 

cityList.Clear();

cityList.AddAll(citySet);

That will do away with all the replica factors from the given list. Note that insertion order may not be retained if a HashSet is used. In case insertion order is to be retained use LinkedHashSet.

Q25. What All Collection Classes Are Inherently Thread-safe?

In the preliminary Collection training like Vector, HashTable and Stack all of the techniques had been synchronized to make these training thread safe. 

Later implementations starting from Java 1.2 have been now not synchronized. 

Classes in java.Util.Concurrent package like ConcurrentHashMap, CopyOnWriteArrayList additionally affords thread protection however with a distinctive implementation that doesn't require making all the strategies synchronized.

Q26. Why Arraylist Is Called Dynamically Growing Array? How That Dynamic Behaviour Is Achieved?

In the case of ArrayList you do not need to anticipate earlier, like within the case of array, how many factors you're going to store in the arraylist. As and while elements are added list keeps growing. That is why ArrayList is referred to as dynamically developing array.

For ArrayList, information structure used for storing factors is array itself. When ArrayList is created it initializes an array with an initial capacity (default is array of length 10). When that restrict is crossed every other array is created that's 1.5 times the unique array and the elements from the old array are copied to the new array.

Q27. Which Collection Classes Implement Random Access Interface?

In Java.Util package the classes that put in force random get entry to interface are - ArrayList, CopyOnWriteArrayList, Stack, Vector.

Q28. What Happens If Hashmap Has Duplicate Keys?

If an attempt is made to feature the equal key two times, it might not purpose any error however the fee that is delivered later will override the previous value. 

As Exp. If you have got a Map, cityMap and you add  values with equal key within the cityMap, Kolkata will override the New Delhi.

CityMap.Placed("5", "New Delhi");

cityMap.Placed("five", "Kolkata");

Q29. What Is Foreach Statement Added In Java 8?

Java 8 has added a purposeful fashion lopping to the Collections. Real benefit of this loop is whilst it's miles used on a stream with the chain of purposeful techniques. If you've got a Map<String, String> then it is able to be looped the usage 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()));

Q30. What Is List Interface?

List interface extends the basis interface Collection and provides behaviour for the gathering that stores a chain of factors. These elements can be inserted or accessed by their function inside the listing using a zero-primarily based index.

Q31. How Can We Synchronize A Collection Or How To Make A Collection Thread-secure?

Collections class has several static techniques that go back synchronized collections. Each of the six center collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap - has one static manufacturing unit 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> list);

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 methods returns a synchronized (thread-safe) Collection subsidized up via the desired series.

Q32. What Is Linkedhashset?

LinkedHashSet is also one of the implementation of the Set interface. Actually LinkedHashSet magnificence extends the HashSet and has no different strategies of its very own.

LinkedHashSet additionally shops particular factors just like different implemetations of the Set interface. How LinkedHashSet differs is that it continues the insertion-order; that is factors inside the LinkedHashSet are stored inside the sequence in which they are inserted. Note that insertion order isn't affected if an detail is re-inserted into the set.

Q33. What Is Linkedhashmap?

LinkedHashMap is also one of the implementation of the Map interface, aside from imposing Map interface LinkedHashMap also extends the HashMap class. So much like HashMap, LinkedHashMap also permits one null key and a couple of null values.

How it differs from other implementations of the Map interface like HashMap and TreeMap is thatLinkedHashMap keeps the insertion order of the factors which me if we iterate a LinkedHashMap we're going to get the keys inside the order wherein they were inserted within the Map. 

LinkedHashMap continues a doubly-related listing strolling through all of its entries and that's the way it continues the generation order.

Q34. Hashmap Vs Linkedhashmap Vs Treemap In Java?

HashMap makes no ensures as to the order of the map.

LinkedHashMap continues the insertion order of the factors which me if we iterate a LinkedHashMap we'll get the keys within the order in which they have been inserted within the Map.

TreeMap shops items in looked after order.

HashMap in addition to LinkedHashMap allows one null as key, a couple of values may be null although.

TreeMap does not permit null as key.

HashMap shops factors in a bucket which in reality is an index of the array.

LinkedHashMap also makes use of the same inner implementation, it also continues a doubly-linked listing running via all of its entries.

TreeMap is a Red-Black tree based NavigableMap implementation.

Performance smart HashMap presents regular time overall performance O(1) for get() and positioned() approach.

LinkedHashMap additionally offers constant time overall performance O(1) for get() and positioned() method but in fashionable a touch slower than the HashMap because it has to preserve a doubly linked listing.

TreeMap gives guaranteed log(n) time value for the containsKey, get, placed and do away with operations.

Q35. What Is Map.Entry In Map?

Map.Entry is an interface in java.Util, in truth Entry is a nested interface in Map interface. Nested interface need to be certified by using the name of the class or interface of which it's miles a member, it's why it's far certified as Map.Entry. 

Map.Entry represents a key/fee pair that forms one detail of a Map. 

The Map.EntrySet method returns a set-view of the map, whose factors are of this class.

As exp. If you have a Map called cityMap then using entrySet approach you may get the set view of the map whose elements are of type Map.Entry, and then using getKey and getValue techniques of the Map.Entry you could get the key and cost pair of the Map.

For(Map.Entry<String, String> access:  cityMap.EntrySet())

   System.Out.Println("Key is " + entry.GetKey() + " Value is " + access.GetValue());

Q36. Difference Between Arraylist And Vector In Java?

ArrayList is not synchronized while Vector is synchronized.

Performance sensible ArrayList is rapid in comparison to Vector as ArrayList is not synchronized.

ArrayList, by means of default, grows by means of 50% in case the preliminary ability is exhausted. In case of Vector the backing array's size is doubled by way of default.

For traversing an ArrayList iterator is used. For traversing Vecor Iterator/Enumerator may be used. Note that Iterator is fail-speedy for both Vector and ArrayList. Enumerator which can be used with Vector isn't fail-rapid.

Q37. How To Sort Arraylist In Java?

Collections magnificence has a static method sort which may be used for sorting an arraylist.

There are  overloaded variations of type approach -

public static <T extends Comparable<? Super T>> void sort(List<T> list) - Sorts the required listing into ascending order, in keeping with the natural ordering of its factors.

Public static <T> void sort(List<T> list, Comparator<? Super T> c) - Sorts the desired listing in keeping with the order brought about through the desired comparator.

If you have a List known as cityList it could be sorted like this - 

Collections.Type(cityList);

Q38. Difference Between Fail-fast Iterator And Fail-secure Iterator?

Fail-fast iterator throws a ConcurrentModificationException if the underlying collection is structurally modified whereas fail-secure iterator would not throw ConcurrentModificationException.

Fail-speedy iterator does not create a duplicate of the collection whereas fail-secure iterator makes a copy of the underlying shape and iteration is accomplished over that image.

Fail-fast iterator affords operations like dispose of, add and set (in case of ListIterator) while in case of fail-secure iterators detail-converting operations on iterators themselves (cast off, set and add) aren't supported. These methods throw UnsupportedOperationException.

Q39. Which Map Implementation Should Be Used If You Want Map Values To Be Sorted By Keys?

TreeMap should be used in this case.

Q40. What Is A Fail-secure Iterator?

An iterator is taken into consideration fail-safe if it does not throw ConcurrentModificationException. ConcurrentModificationException is not thrown because the fail-safe iterator makes a copy of the underlying shape and generation is accomplished over that picture. 

Since new release is performed over a copy of the gathering so interference is not possible and the iterator is guaranteed now not to throw ConcurrentModificationException.

Q41. What Is A Identityhashmap?

IdentityHashMap magnificence implements the Map interface with a hash desk, the usage of reference-equality in region of item-equality whilst evaluating keys (and values). In different words, in an IdentityHashMap, two keys k1 and k2 are taken into consideration identical if and best if (k1==k2). Where as In regular Map implementations (like HashMap) two keys k1 and k2 are taken into consideration identical if and simplest if (k1==null ? K2==null : k1.Equals(k2)).

Note that This class isn't always a popular-motive Map implementation. While this magnificence implements the Map interface, it intentionally violates Map's fashionable settlement, which mandates the use of the equals approach while evaluating objects. This elegance is designed for use best within the rare instances wherein reference-equality semantics are required.

Q42. How To Convert Array To Arraylist In Java?

Arrays elegance includes a static manufacturing unit technique asList() that permits arrays to be regarded as lists.

Public static <T> List<T> asList(T... A)

As Exp.

String cityArray[] = "Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai";

//Converting array to List

List<String> cityList = Arrays.AsList(cityArray);

Q43. What Is The Hashcode() Method?

HashCode() method is gift inside the java.Lang.Object magnificence. This method is used to get a completely unique integer value for a given object. We can see it is use with hash based collections like HashTable or HashMap wherein hashCode() is used to locate the correct bucket location where the precise (key, value) pair is saved.

Q44. How And Why To Synchronize Arraylist In Java?

In order to have better performance maximum of the Collections are not synchronized. Which me sharing an example of arrayList among many threads in which the ones threads are editing (by using including or disposing of the values) the gathering might also result in unpredictable behaviour. 

To synchronize a List Collections.SynchronizedList() approach may be used.

Q45. What Is Randomaccess Interface?

RandomAccess interface is a marker interface utilized by List implementations to indicate that they support speedy (usually regular time) random access. 

Q46. Can We Iterate Through A Map?

Though we cannot iterate a Map as such however Map interface has methods which provide a fixed view of the Map. That set can be iterated. Those two methods are -

Set<Map.Entry<K, V>>entrySet() - This method returns a set that contains the entries within the map. The entries in the set are actually item of type Map.Entry.

Set<K>keySet() - This technique returns a fixed that carries the keys of the map.

There is also a values() technique within the Map that returns a Collection view of the values contained in this map.

Q47. How To Loop/iterate An Arraylist In Java?

There are many approaches to loop/iterate an arrayList in Java. Options are -

for loop

for-every loop

iterator

list iterator

Java eight forEach loop

for-every loop is the high-quality way to iterate a listing if you simply want to traverse sequentially via a list.

Q48. Are Maps Actually Collections Or Why Doesn't Map Extend Collection?

Maps themselves are not collections due to the fact they don't enforce Collection interface.

Q49. Does Hashmap Allow Null Keys And Null Values?

HashMap permits one null key and any variety of null values. If another null secret is delivered it may not purpose any errors. But the price with the new null key will override the cost with old null key.

As exp. If you have a Map, cityMap and also you add two values with null keys within the cityMap, Kolkata will override the New Delhi as simplest one null key's allowed.

CityMap.Placed(null, "New Delhi");

cityMap.Positioned(null, "Kolkata");

Q50. Difference Between Array And Arraylist In Java?

Array is constant in size which is provided at the time of creating an Array. ArrayList grows dynamically and additionally called dynamically developing array.

Array can save primitive types in addition to objects. In ArrayList most effective Objects can be stored.

Arrays may be multi-dimensional whereas ArrayList is usually unidimensional.

As Exp. A two dimensional array may be created as -

Integer myArray[][] = new Integer[4][3];

Performance wise both Array and ArrayList are nearly same as internally ArrayList also makes use of an Array. But there may be overhead of resizing the array and copying the elements to the new Array in case of ArrayList.




CFG