YouTube Icon

Interview Questions.

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

fluid

Top 100+ Java Collections Interview Questions And Answers

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

Answer :

Java Collections Framework affords a wellknown way to address a group of items. Benefits of the Collections Framework are -

High performance, implementation of the Collection classes (ArrayList, LinkedList, HashSet and so forth.) are very efficient and used as-is in maximum of the instances.
Reduced effort as framework already offers several implementations for most of the situations that may be used as-is.
Provides interoperability, as exp. If you are using List interface any implementation that implements List interface can be swapped with the present one.
If you want to increase any series that can be effortlessly performed using the usual interfaces supplied with in the Collections frameworks.
Question 2. Describe The Collection Framework Hierarchy?

Answer :

At the foundation of the Collections framework is Collection interface, it have to be applied by way of any class that defines a set. This interface announces the middle techniques that every series will have, if any elegance doesn't implement any of the technique then it can throw UnsupportedOperationException.

Then there are List and Set interfaces that increase Collection interface and supplied some of its own behaviour in order to be in addition carried out via the lessons that enforce List and Set interfaces respectively. 

There is also a Queue interface that extends collection to offer behaviour of a queue. On the opposite hand there's Map interface which presents center strategies for the Map implementations.

Adv Java Interview Questions
Question 3. Name The Core Collection Classes?

Answer :

AbstractCollection - Implements most of the Collection interface.
AbstractList - Extends AbstractCollection and implements List interface.
AbstractSequentialList - Extends AbstractList to provide sequential get right of entry to.
ArrayList - Extends AbstractList to provide dynamic array implementation.
LinkedList - Extends AbstractSequentialList to put into effect a related list.
AbstractQueue - Extends AbstractCollection and implements Queue interface.
ArrayDeque - Resizable-array implementation of the Deque interface.
PriorityQueue - Extends AbstractQueue to offer a concern-based totally queue.
AbstractSet - Extends AbstractCollection and implements Set interface.
HashSet - Extends AbstractSet backed by way of a HashTable (in reality a HashMap example).
LinkedHashSet - Extends HashSet to offer insertion order interation.
TreeSet - Extends AbstractSet (and implements NavigableSet interface) to provide looked after set.
EnumSet - Extends AbstractSet to be used with Enum factors.
Question four. How Generics Changed The Collection Framework?

Answer :

With JDK5 the Collection framework changed into reengineered to feature generics. That changed into finished to feature "Type Safety" to the collections. Prior to JDK5 (and generics) factors had been stored in collections as Object references, which added the danger of by accident storing incompatible kinds in Collection due to the fact for Collections the entirety changed into Object reference. Which could have resulted in run time blunders whilst seeking to retrieve elements and casting them to the desired kind. 

With the advent of generics now we can explicitly tell which records type is to be stored in the collections, which facilitates in averting the run time blunders. As Collection will throw errors 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 simplest keep string as both key and cost.

Adv Java Tutorial
Question five. What Is For-each Style Loop?

Answer :

Another feature which become introduced to Collection with JDK 5 is for-each fashion loop. Any collection which desires to be the target of the "for-every loop" announcement has to put in force iterable interface.

Using for-each loop is easier than building the iterator to iterate over the collection and can be utilized in maximum of the cases as opposed to the usage of the iterator loop.

If you've got a listing of Strings, that can be iterated the usage of for-each loop like this.

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


J2EE Interview Questions
Question 6. What Is A Diamond Operator?

Answer :

Diamond operator allow the compiler infer the kind arguments for the standard instructions. It is introduced in Java 7. 

As Example - Before JDK7 if we needed to outline 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 replacement the parameterized form of the constructor with an empty set of kind parameters (<>) known as diamond operator.

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

Question 7. What Are The Changes In Collections Framework In Java eight?

Answer :

There are several changes in Collections Framework in Java 8 more often than not prompted by using the inclusion of Lambda expression in Java eight -

Stream API - Stream may be acquired for Collection via the flow() and parallelStream() techniques;

As exp if you have a list of cities in a List and also you need to remove the replica cities from that list it may be achieved as
cityList = cityList.Flow().Distinct().Accumulate(Collectors.ToList());
ForEach loop which can be used with Collection. Spliterators which might be useful in parallel processing wherein numerous threads can itearate/method a part of the gathering.
New strategies are added to Collections like replaceAll, getOrDefault, putIfAbsent in Map.
HashMap, LinkedHashMap and ConcurrentHashMap.Implementation is modified to lessen hash collisions. Instead of connected list a balanced tree is used to save the entries after a positive threshold is reached.
J2EE Tutorial Core Java Interview Questions
Question 8. What Is Foreach Statement Added In Java eight?

Answer :

Java 8 has added a useful style lopping to the Collections. Real advantage of this loop is while it is used on a circulation with the chain of functional strategies. If you have a Map<String, String> then it could be looped the use of ForEach assertion like this - 

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

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

Question 9. What Is Randomaccess Interface?

Answer :

RandomAccess interface is a marker interface utilized by List implementations to signify that they aid speedy (commonly consistent time) random access. 

JSP Interview Questions
Question 10. Which Collection Classes Implement Random Access Interface?

Answer :

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

Core Java Tutorial
Question 11. What All Collection Classes Are Inherently Thread-safe?

Answer :

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

Later implementations beginning from Java 1.2 had been not synchronized. 

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

Java-Springs Interview Questions
Question 12. How Can We Synchronize A Collection Or How To Make A Collection Thread-secure?

Answer :

Collections class has numerous static methods that go back synchronized collections. Each of the six core series interfaces -Collection, Set, List, Map, SortedSet, and SortedMap - has one static factory technique.

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

Adv Java Interview Questions
Question 13. How To Make A Collection Class Immutable?

Answer :

Collections magnificence provides static method to make a Collection unmodifiable. Each of the six core collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap - has one static manufacturing facility approach.

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

JSP Tutorial
Question 14. What Is List Interface?

Answer :

List interface extends the basis interface Collection and provides behaviour for the collection that stores a series of elements. These elements can be inserted or accessed by using their function in the listing the usage of a 0-primarily based index.

Question 15. Which Collection Classes Implement List Interface?

Answer :

Some of the Collection classes that enforce List interface are ArrayList, CopyOnWriteArrayList, LinkedList, Stack, Vector.

JMS(Java Message Service) Interview Questions
Question 16. Why Arraylist Is Called Dynamically Growing Array? How That Dynamic Behaviour Is Achieved?

Answer :

In the case of ArrayList you don't need to count on in advance, like inside the case of array, what number of factors you're going to store inside the arraylist. As and when factors are added list continues growing. That is why ArrayList is referred to as dynamically growing array.

For ArrayList, facts structure used for storing factors is array itself. When ArrayList is created it initializes an array with an initial ability (default is array of duration 10). When that restriction is crossed every other array is created which is 1.Five times the original array and the elements from the old array are copied to the brand new array.

Java-Springs Tutorial
Question 17. How Arraylist Works Internally In Java?

Answer :

Basic statistics structure used by ArrayList to store objects is an array of Object class, that's described like -

temporary Object[] elementData; 

When we add an element to an ArrayList it first verifies whether it has that tons potential within the array to shop new element or not, in case there isn't always then the brand new capacity is calculated that's 50% more than the old capability and the array is elevated with the aid of that plenty ability (Actually uses Arrays.CopyOf which returns the authentic array multiplied to the new length)

Java applet Interview Questions
Question 18. How To Add Elements To An Arraylist?

Answer :

List gives a way add(E e) which appends particular element to the cease of the list. Using add(E e) approach will imply preserve including factors sequentially to the list.
Another add technique - add(int index, E element) inserts the desired detail at the specified position in this list.
Third method addAll(int index, Collection<? Extends E> c) inserts all of the elements in the distinctive series into this listing, beginning at the specified position.
J2EE Interview Questions
Question 19. Does Arraylist Allow Duplicate Elements?

Answer :

Yes. List allows duplicate elements to be delivered.

Java Tutorial
Question 20. Does Arraylist Allow Null?

Answer :

In ArrayList any quantity of nulls may be brought.

Java Interview Questions
Question 21. How To Join Two Or More Arraylists?

Answer :

List gives a technique addAll to enroll in  or extra lists in Java. 

If you've got one list cityList and any other List secondCityList then you could be a part of them the usage of addAll like this - 

cityList.AddAll(secondCityList);

Question 22. How To Remove Elements From An Arraylist?

Answer :

ArrayList offers several techniques to put off elements from the List. Since ArrayList internally makes use of array to shop factors, one factor to note is that when an detail is removed from the List the closing factors need to be shifted to fill the space created within the underlying array.

Clear() - Removes all the factors from this listing.
Take away(int index) - Removes the detail at the required position in this list.
Cast off(Object o) - Removes the first occurrence of the desired detail from this listing, if it is gift.
RemoveAll(Collection<?> c) - Removes from this listing all of its factors which are contained in the detailed collection.
RemoveIf(Predicate<? Super E> clear out) - Removes all of the elements of this collection that satisfy the given predicate.
Java 8 Tutorial
Question 23. How To Remove Duplicate Elements From An Arraylist?

Answer :

We can use a HashSet to do the task of doing away with the duplicate elements. HashSet best stores precise factors and we will use that function of HashSet to dispose of duplicates.

If you have a List referred to as cityList you could create a HashSet the usage of this list - 

Set<String> citySet = new HashSet<String>(cityList);
then add this set lower back to the cityList 
cityList.Clear();
cityList.AddAll(citySet);

That will remove all of the replica elements from the given listing. Note that insertion order may not be retained if a HashSet is used. In case insertion order is to be retained use LinkedHashSet.

Java 8 Interview Questions
Question 24. How To Loop/iterate An Arraylist In Java?

Answer :

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

for loop
for-each loop
iterator
list iterator
Java 8 forEach loop
for-each loop is the exceptional manner to iterate a listing in case you just want to traverse sequentially through a list.

Core Java Interview Questions
Question 25. What Is Listiterator In Java?

Answer :

ListIterator presents the capability to iterate a list in each guidelines. The thrilling point about listing iterator is that it has no modern-day detail. Its present day cursor position always lies between the element that could be lower back by way of a call to previous() and the detail that might be returned by a name to subsequent().

Question 26. How To Sort Arraylist In Java?

Answer :

Collections class has a static method kind which can be used for sorting an arraylist.

There are  overloaded versions of kind technique -

public static <T extends Comparable<? Super T>> void sort(List<T> list) - Sorts the required list into ascending order, consistent with the herbal ordering of its elements.
Public static <T> void sort(List<T> listing, Comparator<? Super T> c) - Sorts the specified listing in line with the order brought on by using the desired comparator.
If you've got a List called cityList it may be looked after like this - 

Collections.Type(cityList);

Java Programmer Interview Questions
Question 27. How To Sort Arraylist Of Strings In Descending Order?

Answer :

Collections.Sort() approach will kind the ArrayList of String in ascending order. 

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

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

JSP Interview Questions
Question 28. How And Why To Synchronize Arraylist In Java?

Answer :

In order to have better overall performance most of the Collections are not synchronized. Which way sharing an instance of arrayList amongst many threads in which the ones threads are modifying (by using including or disposing of the values) the collection may additionally bring about unpredictable behaviour. 

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

Question 29. How To Convert Arraylist To Array In Java?

Answer :

Within Collection interface there are two versions of toArray() which may be used to transform ArrayList to array.

Object[] toArray()
<T> T[] toArray(T array[])
The first model returns an array of Object. 

The second model returns an array containing the elements of the listing. Normally we go with the second one version as it returns the array of the identical kind as List.

If you have a List known as cityList, it could be converted to an array like this -

String cityArray[] = new String[cityList.Size()];   
cityArray = cityList.ToArray(cityArray);

Question 30. How To Convert Array To Arraylist In Java?

Answer :

Arrays class contains a static factory technique asList() that lets in arrays to be considered 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);

Question 31. How Is The Performance Of An Arraylist?

Answer :

Adding an detail - If you are including at the cease using upload(E e) method it is O(1). In the worst case it could go to O(n). That will occur in case you upload extra factors than the capacity of the underlying array.
Retrieving an detail - Since ArrayList internally uses an array to save elements so get(int index) method going to that index immediately in the array. So, for ArrayList get(int index) is O(1).
Removing an element - If you are disposing of the use of the put off(int index) approach then, in case of ArrayList getting to that index is rapid however casting off will imply shuffling the remaining factors to fill the distance created through the eliminated element with in the underlying array. Thus it is able to be said do away with(int index) operation is O(n - index) for the arraylist.
Question 32. What Is Linkedlist Class In Java? How Is It Implemented?

Answer :

LinkedList elegance in Java implements List and Deque interfaces and LinkedList implements it using doubly linkedlist.

Within the LinkedList implementation there's a non-public elegance Node which offers the shape for a node in a doubly related listing. It has item variable for containing the cost and two reference to Node magnificence itself for connecting to subsequent and previous nodes.

Question 33. What Is Deque Interface In Java?

Answer :

Java.Util.Deque is an interface in Java which extends Queue interface and provides guide for detail insertion and removal at both ends. The call deque is short for "double ended queue" and is commonly said "deck".

Some of the implementing training of the Deque interface are LinkedList, ConcurrentLinkedDeque, LinkedBlockingDeque. Note that addFirst() and addLast() strategies supplied inside the LinkedList implementation are specific via the Deque interface.

Java-Springs Interview Questions
Question 34. Difference Between Arraylist And Linkedlist In Java?

Answer :

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

LinkedList is implemented the use of a doubly linked listing concept wherein as ArrayList internally makes use of an array of Objects which may be resized dynamically
For LinkedList upload(e Element) is always O(1) wherein as for ArrayList upload(e Element) operation runs in amortized consistent time, this is, including n factors calls for O(n) time.
For LinkedList get(int index) is O(n) wherein as for ArrayList get(int index) is O(1).
If you're getting rid of using the remove(int index) method then for LinkedList elegance it is going to be O(n). In case of ArrayList attending to that index is rapid however getting rid of will imply shuffling the remaining elements to fill the space created by means of the eliminated detail with in the underlying array.
Question 35. Difference Between Arraylist And Vector In Java?

Answer :

ArrayList isn't synchronized while Vector is synchronized.
Performance clever ArrayList is speedy in contrast to Vector as ArrayList isn't synchronized.
ArrayList, by using default, grows through 50% in case the initial capacity is exhausted. In case of Vector the backing array's size is doubled through default.
For traversing an ArrayList iterator is used. For traversing Vecor Iterator/Enumerator can be used. Note that Iterator is fail-fast for both Vector and ArrayList. Enumerator which can be used with Vector isn't always fail-speedy.
Question 36. Difference Between Array And Arraylist In Java?

Answer :

Array is constant in size which is supplied on the time of creating an Array. ArrayList grows dynamically and additionally known as dynamically developing array.
Array can shop primitive kinds as well as items. In ArrayList only Objects can be saved.
Arrays can be multi-dimensional while ArrayList is continually 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 equal 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.
JMS(Java Message Service) Interview Questions
Question 37. What Is An Iterator?

Answer :

Iterator is an interface which is part of the Java Collections framework. An Iterator permits you to iterate a collection. Iterators additionally permit the caller to remove factors from the underlying collection throughout the new release.

Collection instructions provide iterator method which returns an iterator. This iterator can be used to traverse a group.

As exp. If there is a set known as citySet, an iterator on this set can be acquired as -

Iterator<String> itr = citySet.Iterator();
while (itr.HasNext()) 
    String town = (String) itr.Next();
    System.Out.Println("city " + town);        


Question 38. Difference Between Iterator And Listiterator?

Answer :

Iterator may be acquired on any Collection elegance like List or Set. But ListIterator can best be used to traverse a List.
Iterator handiest actions in one path the usage of next() approach. ListIterator can iterate in each directions using next() and former() strategies.
Iterator always begin at the beginning of the gathering.

ListIterator may be acquired at any point.

As Exp. If you have got a List of integers numberList, you may acquire a ListIterator from the 1/3 index of this List.
ListIterator<Integer> ltr = numberList.ListIterator(three);

ListIterator presents an upload(E e) technique which isn't always there in Iterator. Upload(E e) inserts the specified element into the list.
ListItearator additionally offers set technique. Void set(E e) replaces the last element again by using subsequent() or preceding() with the specified element
Question 39. Why Iterator Doesn't Have Add Method Whereas Listiterator Has Add Method?

Answer :

Iterator can be obtained on any Collection elegance like List or Set so settlement for Iterator makes no guarantees approximately the order of iteration. 

But ListIterator can handiest be used to traverse a List so it does assure the order of the generation. That is why ListIterator affords an upload operation.

Question forty. What Is Fail Fast Iterator?

Answer :

An iterator is taken into consideration fail-speedy if it throws a ConcurrentModificationException below both of the subsequent  conditions:

In multi-threaded environment, if one thread is trying to alter a Collection whilst some other thread is iterating over it.
Even with unmarried thread, if a thread modifies a group immediately while it's far iterating over the gathering with a fail-speedy iterator, the iterator will throw this exception.
Fail-speedy iterator will throw a ConcurrentModificationException if the underlying collection is structurally changed in any manner besides thru the iterator's own take away or add (if relevant as in list-iterator) strategies.

Note that structural modification is any operation that provides or deletes one or extra elements; merely setting the fee of an element (in case of listing) or converting the value associated with an current key (in case of map) isn't a structural amendment.

Java applet Interview Questions
Question forty one. What Is A Fail-safe Iterator?

Answer :

An iterator is taken into consideration fail-safe if it does now not throw ConcurrentModificationException. ConcurrentModificationException isn't thrown as the fail-safe iterator makes a copy of the underlying shape and generation is completed over that image. 

Since new release is accomplished over a duplicate of the collection so interference is not possible and the iterator is assured now not to throw ConcurrentModificationException.

Question 42. Difference Between Fail-fast Iterator And Fail-secure Iterator?

Answer :

fail-speedy iterator throws a ConcurrentModificationException if the underlying series is structurally changed whereas fail-secure iterator would not throw ConcurrentModificationException.
Fail-rapid iterator doesn't create a copy of the collection while fail-safe iterator makes a copy of the underlying shape and iteration is achieved over that photo.
Fail-speedy iterator presents operations like do away with, upload and set (in case of ListIterator) whereas in case of fail-safe iterators detail-changing operations on iterators themselves (put off, set and add) are not supported. These techniques throw UnsupportedOperationException.
Java Interview Questions
Question forty three. Can We Iterate Through A Map?

Answer :

Though we can not iterate a Map as such however Map interface has methods which offer a hard and fast view of the Map. That set can be iterated. Those  techniques are -

Set<Map.Entry<K, V>>entrySet() - This method returns a fixed that carries the entries in the map. The entries in the set are in reality object of type Map.Entry.
Set<K>keySet() - This method returns a set that includes the keys of the map.
There is likewise a values() method in the Map that returns a Collection view of the values contained in this map.

Question forty four. Are Maps Actually Collections Or Why Doesn't Map Extend Collection?

Answer :

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

Question 45. What Is Map.Access In Map?

Answer :

Map.Entry is an interface in java.Util, in fact Entry is a nested interface in Map interface. Nested interface have to be certified by using the name of the magnificence or interface of which it's miles a member, that is why it's far qualified as Map.Entry. 

Map.Entry represents a key/value pair that bureaucracy one element of a Map. 

The Map.EntrySet approach returns a group-view of the map, whose elements are of this magnificence.

As exp. If you have a Map called cityMap then the usage of entrySet method you could get the set view of the map whose elements are of kind Map.Entry, and then the usage of 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 " + access.GetKey() + " Value is " + entry.GetValue());

Question 46. Does Hashmap Allow Null Keys And Null Values?

Answer :

HashMap lets in one null key and any quantity of null values. If some other null key is brought it may not cause any mistakes. But the price with the new null key will override the fee with antique null key.

As exp. If you've got a Map, cityMap and also you add  values with null keys in the cityMap, Kolkata will override the New Delhi as handiest one null secret is allowed.

CityMap.Positioned(null, "New Delhi");
cityMap.Put(null, "Kolkata");

Question 47. What Happens If Hashmap Has Duplicate Keys?

Answer :

If an attempt is made to add the equal key twice, it might not cause any mistakes but the value that's introduced later will override the preceding price. 

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

CityMap.Put("5", "New Delhi");
cityMap.Placed("five", "Kolkata");

Question forty eight. What Is Hash-collision In Hash Based Collections?

Answer :

In HashMap, the use of the key, a Hash is calculated and that hash fee makes a decision wherein bucket the specific Map.Entry item will live.

Hash collision method multiple key having the identical calculated hash value thus saved inside the identical bucket. In HashMap, if so Entry objects are stored as a related-listing with inside the same bucket.

Question forty nine. What Is The Hashcode() Method?

Answer :

hashCode() method is gift in the java.Lang.Object class. This approach is used to get a completely unique integer price for a given object. We can see it is use with hash based collections like HashTable or HashMap where hashCode() is used to discover the ideal bucket vicinity in which the specific (key, price) pair is stored.

Question 50. What Is Equals() Method?

Answer :

equals() approach is present within the java.Lang.Object class. It is used to decide the equality of two gadgets.

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

Answer :

The default implementation of equals() technique in the Object elegance 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 just returns integer price of the memory deal with of the item.

It will become very essential to override these  strategies in case we are the usage of a custom object as key in a hash based series. 

In that case we can not rely on the default implementation furnished via the Object magnificence and want to provide custom implementation of hashCode() and equals() technique.

If  gadgets Obj1 and Obj2 are identical in step with their equals() approach then they have to have the identical hash code too. Though the vice-versa isn't true that is if two gadgets have the identical hash code then they do no longer need to be same too.

Question fifty two. Which Map Implementation Should Be Used If You Want To Retain The Insertion Order?

Answer :

LinkedHashMap need to be utilized in this situation.

Question fifty three. What Is Linkedhashmap?

Answer :

LinkedHashMap is also one of the implementation of the Map interface, aside from implementing Map interface LinkedHashMap also extends the HashMap elegance. So similar to HashMap, LinkedHashMap additionally permits one null key and multiple null values.

How it differs from other implementations of the Map interface like HashMap and TreeMap is thatLinkedHashMap maintains the insertion order of the factors because of this if we iterate a LinkedHashMap we will get the keys within the order wherein they have been inserted in the Map. 

LinkedHashMap keeps a doubly-linked list running through all of its entries and that is how it maintains the iteration order.

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

Answer :

TreeMap must be utilized in this example.

Question fifty five. What Is Treemap In Java?

Answer :

TreeMap is also one of the implementation of the Map interface like HashMap and LinkedHashMap. TreeMap class implements the NavigableMap interface and extends the AbstractMap magnificence.

How it differs from different implementations of the Map interface is that gadgets in TreeMap are stored in looked after order. The factors are ordered using their herbal ordering or a comparator may be provided at map advent time to offer custom ordering.

One crucial factor approximately TreeMap is, though HashMap and LinkedHashMap allow one null as key, TreeMap would not permit null as key. Any try to upload null in a TreeMap will result in a NullPointerException.

Question 56. What Is A Weakhashmap?

Answer :

WeakHashMap is a Hash table based implementation of the Map interface, with vulnerable keys. An entry in a WeakHashMap will routinely be removed whilst its key is no longer in ordinary use. Which means storing best susceptible references allows rubbish collector to dispose of the entry (key-price pair) from the map when its key isn't always referenced outdoor of the WeakHashMap.

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

Map weakHashMap = new WeakHashMap();

Question fifty seven. What Is A Identityhashmap?

Answer :

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

Note that This class isn't always a widespread-cause Map implementation. While this magnificence implements the Map interface, it deliberately violates Map's standard contract, which mandates using the equals approach when evaluating gadgets. This magnificence is designed to be used simplest within the uncommon instances wherein reference-equality semantics are required.

Question 58. Difference Between Hashmap And Hashtable In Java?

Answer :

Though both HashTable and HashMap keep elements as a (key, fee) pair and use hashing technique to keep elements, furthermore from Java v1.2, HashTable magnificence changed into retrofitted to implement the Map interface, making it a member of the Java Collections Framework. But there are sure difference among the two -

HashMap isn't synchronized where as HashTable is synchronized.
HashMap permits one null value as a key and any quantity of null values wherein as HashTable does not permit null values both as key or as price.
For traversing a HashMap an iterator can be used. For traversing a HashTable either an iterator or Enumerator may be used. The iterator used for both HashMap and HashTable is fail-fast but the enumerator used with HashTable is fail-secure.
Performance clever HashMap is quicker than the HashTable motive being HashMap isn't always synchronized.
Question 59. Hashmap Vs Linkedhashmap Vs Treemap In Java?

Answer :

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

LinkedHashMap keeps the insertion order of the elements which means if we iterate a LinkedHashMap we'll get the keys inside the order wherein they were inserted within the Map.

TreeMap stores gadgets in looked after order.

HashMap in addition to LinkedHashMap lets in one null as key, more than one values can be null even though.

TreeMap does not allow null as key.

HashMap shops elements in a bucket which virtually is an index of the array.

LinkedHashMap also makes use of the same inner implementation, it also keeps a doubly-related list running via all of its entries.

TreeMap is a Red-Black tree based totally NavigableMap implementation.

Performance sensible HashMap gives regular time overall performance O(1) for get() and put() method.

LinkedHashMap additionally offers steady time performance O(1) for get() and positioned() technique but in trendy a little slower than the HashMap because it has to preserve a doubly connected list.

TreeMap presents assured log(n) time price for the containsKey, get, positioned and remove operations.
Question 60. How Does Hashset Internally Works In Java?

Answer :

HashSet internally uses HashMap to shop it's factors. But it differs from HashMap on  points.

HashSet most effective shops particular values i.E. No duplicates are allowed.
In HashSet we've upload(E e) method which takes just the detail to be added as parameter not the (key, fee) pair.
Question sixty one. Which Set Implementation Should Be Used If You Want The Insertion Order To Be Maintained?

Answer :

LinkedHashSet must be utilized in this case.

Question sixty two. What Is Linkedhashset?

Answer :

LinkedHashSet is likewise one of the implementation of the Set interface. Actually LinkedHashSet magnificence extends the HashSet and has no other techniques of its own.

LinkedHashSet also stores specific elements much like other implemetations of the Set interface. How LinkedHashSet differs is that it maintains the insertion-order; this is elements in the LinkedHashSet are stored in the series wherein they're inserted. Note that insertion order isn't always affected if an element is re-inserted into the set.




CFG