Java Collections Interview Questions (2023)

Java Collections Interview Questions are probably the most requested interview questions for a Java Developer. In JDK 1.2 “Assortment Framework” was once offered that accommodates all of the assortment categories and interfaces. Assortment in Java is a framework that gives a mechanism to retailer and manipulate the selection of items. It lets in builders to get right of entry to prepackaged knowledge constructions and algorithms for manipulating knowledge. The Collections in Java supply a number of categories (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet) and interfaces (Set, Checklist, Queue, Deque). 

Java Collections Interview Questions

 

Right here, we’ve got supplied Most sensible 50 Java Collections Interview Questions with Solutions that will let you to crack the Java Developer Interview.

Java Collections Interview Questions For Freshers and Skilled

1. What’s Assortment in Java?

The time period assortment refers to a bunch of items represented as one unit. Categories within the Java assortment elegance hierarchy are divided into two “root” interfaces: Assortment (java.util.Assortment) and Map (java.util.Map). Phrases that you’re going to stumble upon whilst finding out concerning the assortment in Java:

  • Assortment Framework: Java’s Assortment Framework defines categories and interfaces for representing teams of items as a unmarried entity. C++ builders can evaluate the Assortment framework with STL (Same old Template Library) and Container Framework with the Assortment Framework if they arrive from a C++ background.
  • Assortment Interface: A category’s interface specifies what it will have to do, now not how. In different phrases, it’s the blueprint for the category. This interface supplies the most typical strategies for all assortment items which might be a part of the Assortment Framework. Then again, it represents the person object as an entire.
  • Collections Elegance: A member of Assortment Framework, it is a part of java.util bundle. The gathering object is supplied with many application strategies on this elegance.

For more info, consult with the thing – Collections in Java

2. What’s a Framework in Java?

Frameworks are units of categories and interfaces that supply a ready-made structure. It’s not essential to outline a framework as a way to put into effect new options or categories. Consequently, an optimum object-oriented design features a framework containing a selection of categories that every one carry out same duties. The framework can be utilized in quite a few techniques, akin to by means of calling its strategies, extending it, and supplying “callbacks”, listeners, and different implementations. One of the vital common frameworks in java are:

  • Spring
  • Hibernate
  • Struts
  • Google Internet Toolkit (GWT)
  • JavaServer Faces (JSF)

3. What’s the distinction between Array and Assortment in Java?

Arrays are a selection of similar-typed variables with a commonplace title in Java. There are some variations between arrays in Java and C/C++. Alternatively, Collections are teams of particular person items that shape a unmarried entity referred to as the selection of items.

Arrays Assortment
Arrays are fastened in measurement this is when we create an array we will now not building up or lower in response to our necessities. The gathering is growable in nature and is in response to our necessities. We will be able to building up or lower of measurement.
With admire to reminiscence, Arrays don’t seem to be beneficial to be used. With admire to reminiscence, collections are beneficial to be used.
With admire to functionality, Arrays are beneficial to be used. With admire to functionality, collections don’t seem to be beneficial to be used.
Arrays can dangle solely homogeneous knowledge sorts components. Assortment can dangle each homogeneous and heterogeneous components.

For more info, consult with the thing – Distinction Between Arrays and Collections in Java

4.  What are the more than a few interfaces utilized in Java Collections Framework?

The gathering is referred to as the foundation of the gathering hierarchy. Collections constitute teams of items referred to as components. The java platform does now not supply any direct implementation of this interface however the Assortment interface is being carried out by means of Checklist and Set categories.

  • Assortment interface
  • Checklist interface
  • Set interface
  • Queue interface
  • Dequeue interface
  • Map interface

5. Provide an explanation for the hierarchy of the Assortment framework in Java.

All categories and interfaces required by means of the gathering framework are contained within the application bundle (java. util). Assortment frameworks have an interface referred to as an iterable interface, which permits the iterator to iterate over all collections. Along with this interface, the principle assortment interface acts as a root for the gathering framework. All of the collections lengthen this assortment interface thereby extending the homes of the iterator and the strategies of this interface. The next determine illustrates the hierarchy of the gathering framework. 

Java Collection Hierarchy

Java Assortment Hierarchy

6. What are some great benefits of the gathering Framework?

Benefits of the Assortment Framework: Because the loss of a set framework gave upward thrust to the above set of disadvantages, the next are some great benefits of the gathering framework. 

  • Constant API: The API has a fundamental set of interfaces like Assortment, Set, Checklist, or Map, all of the categories (ArrayList, LinkedList, Vector, and many others) that put into effect those interfaces have some commonplace set of strategies.
     
  • Reduces programming effort: A programmer doesn’t have to fret concerning the design of the Assortment however relatively he can center of attention on its absolute best use in his program. Subsequently, the fundamental thought of Object-oriented programming (i.e.) abstraction has been effectively carried out.
     
  • Will increase program velocity and high quality: Will increase functionality by means of offering high-performance implementations of helpful knowledge constructions and algorithms as a result of on this case, the programmer don’t need to recall to mind the most productive implementation of a selected knowledge construction. He can merely use the most productive implementation to vastly spice up the functionality of his set of rules/program.

7. What’s ArrayList in Java? 

ArrayList is part of the Java assortment framework and this can be a elegance of java.util bundle. It supplies us with dynamic arrays in Java. The primary benefits of ArrayList are, if we claim an array then it’s had to point out the scale however in ArrayList, it’s not had to point out the scale of ArrayList if you wish to point out the scale then you’ll do it.

Image of Array List

Symbol of Array Checklist

For more info, consult with the thing – ArrayList in Java

8. What’s the distinction between Assortment and Collections?

                              Assortment                                           Collections
It’s an interface. This is a application elegance.
It’s used to constitute a bunch of particular person items as a unmarried unit.  It defines a number of application strategies which might be used to perform on assortment.                                                                                                    
The Assortment is an interface that accommodates a static way since java8. The Interface too can comprise summary and default strategies. It accommodates solely static strategies.

For more info, consult with the thing – Assortment vs Collections in Java with Instance

9. Distinction between ArrayList and LinkedList within the java assortment framework?

ArrayList and LinkedList

ArrayList and LinkedList

ArrayList LinkedList
This elegance makes use of a dynamic array to retailer the weather in it. With the creation of generics, this elegance helps the garage of all forms of items. This elegance makes use of a doubly related listing to retailer the weather in it. Very similar to the ArrayList, this elegance additionally helps the garage of all forms of items.
Manipulating ArrayList takes extra time because of the interior implementation. Every time we take away a component, internally, the array is traversed and the reminiscence bits are shifted. Manipulating LinkedList takes much less time in comparison to ArrayList as a result of, in a doubly-linked listing, there’s no thought of transferring the reminiscence bits. The listing is traversed and the reference hyperlink is modified.
This elegance implements a Checklist interface. Subsequently, this acts as a listing. This elegance implements each the Checklist interface and the Deque interface. Subsequently, it could act as a listing and a deque.
This elegance works higher when the appliance calls for storing the knowledge and getting access to it. This elegance works higher when the appliance calls for manipulation of the saved knowledge.

For more info, consult with the thing – ArrayList vs LinkedList in Java

10. What’s an iterator?

Java’s Assortment framework makes use of iterators to retrieve components one after the other. This iterator is common since it may be used with any form of Assortment object. The usage of Iterator, we will carry out each studying and doing away with operations. That is an advanced model of Enumeration with the addition of doing away with components. When enumerating components in all Assortment framework carried out interfaces, akin to Set, Checklist, Queue, Deque, and all carried out categories of Map, an Iterator will have to be used. The one cursor to be had for all the assortment framework is the iterator. The usage of the iterator() way within the Assortment interface, you’ll create an iterator object.

Syntax:

Iterator itr = c.iterator();

Word: Right here “c” is any Assortment object. itr is of kind Iterator interface and refers to “c”.

For more info, consult with the thing – Iterators in Java

11. What’s the distinction between an Iterator and an Enumeration?

A big distinction between iterator and enumeration is that iterators have a take away() way whilst enumerations don’t. Thus, the usage of Iterator we will manipulate items by means of including and doing away with them from collections. Since enumeration can solely traverse items and fetch them, it behaves like a read-only interface.

For more info, consult with the thing –  Distinction between Iterator and Enumeration

12. What’s the distinction between Checklist and Set in Java

A big distinction between a Checklist and a Set is {that a} Checklist can comprise reproduction components whilst a suite accommodates solely distinctive components. The listing is Ordered and maintains the order of the thing to which they’re added. The set is unordered.

Checklist Set
The Checklist is an listed collection. The Set is a non-indexed collection.
The listing lets in reproduction components The set doesn’t permit reproduction components.
Parts by means of their place may also be accessed. Place get right of entry to to components isn’t allowed.
More than one null components may also be saved. Null components can retailer solely as soon as.
Checklist implementations are ArrayList, LinkedList, Vector, Stack Set implementations are HashSet, LinkedHashSet.

For more info, consult with the thing – Distinction Between Checklist and Set in Java

13. What are the most productive practices for Java Collections Framework?

Following are one of the most absolute best practices whilst the usage of Java Collections:

  • Techniques will have to be written as interfaces, now not implementations, so we will regulate the implementation later.
  • Every time conceivable, use Generics to verify kind protection and keep away from ClassCastExceptions.
  • Opting for the precise form of assortment in response to the desire. As an example, if the scale is fastened, we may need to use an Array over an ArrayList. When iterating over the Map, we will have to use LinkedHashMap. Set is one of the best ways to keep away from duplicates.
  • Use immutable categories supplied by means of JDK as keys in Map to keep away from implementation of hashCode() and equals().
  • With the intention to building up the clarity of the code, we will have to use isEmpty() as an alternative of discovering the scale of the gathering and evaluating it to 0.
  • Quite than writing your individual implementation, use the Collections application elegance to get read-only, Synchronized, or empty collections as an alternative. It complements code reuse whilst leading to higher steadiness.

14. What’s a concern queue in Java?

PriorityQueues are used to procedure items in keeping with their precedence. Queues practice the First-In-First-Out set of rules, however infrequently the weather of the queue want to be processed in keeping with their precedence, which is the place PriorityQueue comes into play. Precedence queues are in response to precedence tons. The weather of the concern queue are ordered in keeping with the herbal ordering, or by means of a Comparator supplied at queue building time, relying on which constructor is used.  

Priority Queues in Java

Precedence Queues in Java

Declaration:

public elegance PriorityQueue<E> extends AbstractQueue<E> implements Serializable

the place E is the kind of components held on this queue

The category implements Serializable, Iterable<E>, Assortment<E>, and Queue<E> interfaces.

15. What’s the distinction between Checklist, set, and map in java?

Checklist

Set

Map

The listing interface lets in reproduction components

The set does now not permit reproduction components.

The map does now not permit reproduction components

The listing maintains insertion order.

The set does now not take care of any insertion order. 

The map additionally does now not take care of any insertion order. 

We will be able to upload any choice of null values.

However within the set virtually just one null price.

The map lets in a unmarried null key at maximum and any choice of null values.

The listing implementation categories are Array Checklist and LinkedList.

Set implementation categories are HashSet, LinkedHashSet, and TreeSet. 

Map implementation categories are HashMap, HashTable, TreeMap, ConcurrentHashMap, and LinkedHashMap.

For more info, consult with the thing – Distinction between Checklist, Set, and Map in Java

16. What’s the distinction between Queue and Stack?

Stack Queue
Stacks works at the LIFO theory, this means that that the component inserted on the final would be the first component that will probably be taken out. Queues paintings at the FIFO theory, this means that that the component inserted first would be the first component that will probably be taken out.
In stacks, insertion, and deletions happen solely from the highest. In queues, insertion happens on the rear of the listing and deletion takes position from the entrance of the listing.
Insert operation is known as push operation. Insert operation is known as enqueue operation.
Delete operation is known as pop operation. Delete operation is known as dequeue operation.
The highest of a stack at all times issues to the final component within the listing, which is the one pointer used to get right of entry to the listing. Two tips are maintained for getting access to queues. The entrance pointer issues to the primary inserted component, and the rear pointer issues to the final inserted component.

16. What’s Enumset?

The EnumSet is an implementation of the Set interface in particular for enumeration-type items. The Enumset extends AbstractSet elegance and implements Set Interface in Java. The EnumSet elegance is a member of the Java Collections Framework & isn’t synchronized. Exceptions akin to ConcurrentModificationException are by no means thrown by means of the iterator, which is weakly constant.

EnumSet in Java

EnumSet in Java

Syntax: 

public summary elegance EnumSet<E extends Enum<E>> 

Right here, E specifies the weather. E will have to lengthen Enum, which enforces the requirement that the weather will have to be of the desired enum kind.

For more info, consult with the thing – EnumSet in Java

17. What’s BlockingQueue in Java?

The BlockingQueue interface in Java is added in Java 1.5 at the side of more than a few different concurrent Application categories like ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrrayList, and many others. The BlockingQueue interface helps glide regulate (along with queue) by means of introducing blockading if both BlockingQueue is complete or empty. A thread seeking to enqueue a component in a complete queue is blocked till any other thread makes area within the queue, both by means of dequeuing a number of components or clearing the queue utterly. In a similar way, it blocks a thread seeking to delete from an empty queue till any other threads insert an merchandise. BlockingQueue does now not settle for a null price. If we attempt to enqueue the null merchandise, then it throws NullPointerException.

Utilization of BlockingQueue 

Blocking Queue in Java

Blocking off Queue in Java

The Hierarchy of BlockingQueue

Hierarchy of Blocking Queue in Java

Hierarchy of Blocking off Queue in Java

Declaration:

public interface BlockingQueue<E> extends Queue<E>

Right here, E is the kind of components saved within the Assortment.

For more info, consult with the thing – BlockingQueue Interface in Java

18. What’s the hashCode()?

Image to demonstrate Java Hash Code

Symbol to show Java Hash Code

hashCode() way returns the hashcode price as an Integer. It’s explained within the Java Object elegance which computes the hash values of given enter items. Hashcode price is most commonly utilized in hashing-based collections like HashMap, HashSet, HashTable….and many others. This technique will have to be overridden in each and every elegance which overrides the equals() way.

Syntax :

public int hashCode()

// This technique returns the hash code price 
// for the thing on which this system is invoked.

For more info, consult with the thing – equals() and hashCode() strategies in Java

19. Distinguish between ArrayList and Vector within the Java Assortment Framework.

In assortment interviews, this query is incessantly requested; on the other hand, Vector is synchronized while ArrayList isn’t. ArrayList is quicker than Vector. ArrayList’s Array measurement is greater by means of 50% when wanted, whilst Vector’s capability is doubled each time it’s wanted.

Array List vs Vector in java

Array Checklist vs Vector in java

ArrayList Vector
ArrayList isn’t Synchronized The vector is synchronized.
The dimensions of ArrayList is incremented as much as 50% of the present array measurement if the choice of components exceeds its capability. The dimensions of ArrayList is incremented as much as 100% of the present array measurement if the choice of components exceeds its capability.
ArrayList is immediate as a result of it’s non-Synchronized. Vector is slower as it’s synchronized.
The iterator interface is used to traverse the weather An iterator interface or Enumeration can be utilized to traverse the vector.

For more info, consult with the thing – Vector vs ArrayList in Java

20. Differentiate between Iterator and ListIterator.

Iterator ListIterator
Can traverse components found in Assortment solely within the ahead path. Can traverse components provide within the Assortment each within the ahead and backward instructions.
Is helping to traverse Map, Checklist, and Set. Can solely traverse Checklist and now not the opposite two.
Indexes can’t be got by means of the usage of Iterator. It has strategies like nextIndex() and previousIndex() to acquire indexes of components at any time whilst traversing the Checklist.
Can’t regulate or change components provide within the Assortment We will be able to regulate or change components with the assistance of set(E e)

For more info, consult with the thing – Distinction Between an Iterator and ListIterator

21. What’s the distinction between an Iterator and an Enumeration?

Iterator: This is a common iterator as we will use it on any Assortment object. Via the usage of an Iterator, we will carry out each learn and take away operations. 

Syntax: 

// Right here "c" is any Assortment object. itr is of
// kind Iterator interface and refers to "c"
Iterator itr = c.iterator();

Enumeration: Enumeration (or enum) is a user-defined knowledge kind. It’s basically used to assign names to integral constants, the names make a program simple to learn and take care of. 

Syntax: 

// A easy enum instance the place enum is asserted 
// outdoor any elegance (Word enum key phrase as an alternative of 
// elegance key phrase) 
enum Colour 
{ 
    RED, GREEN, BLUE; 
}
Iterator Enumeration
The iterator is a common cursor as it’s appropriate to all of the assortment categories. Enumeration isn’t a common cursor because it applies solely to legacy categories.
The iterator has the take away() way. Enumeration does now not have the take away() way.
The iterator can do changes (e.g the usage of the take away() way which gets rid of the component from the Assortment all through traversal). The enumeration interface acts as a read-only interface, one can’t do any changes to the Assortment whilst traversing the weather of the Assortment.
Iterator isn’t a legacy interface. Iterator can be utilized for the traversal of HashMap, LinkedList, ArrayList, HashSet, TreeMap, and TreeSet. Enumeration is a legacy interface this is used for traversing Vector, and Hashtable.

For more info, consult with the thing – Distinction between Iterator and Enumeration 

22. What are the options of Java Hashmap?

HashMap is very similar to HashTable, however it’s unsynchronized. It lets in us to retailer the null keys as neatly, however there will have to be just one null key object and there may also be any choice of null values.  This elegance makes no promises as to the order of the map. To make use of this elegance and its strategies, you want to import java.util. HashMap bundle or its superclass.
 

HashMap in Java

HashMap in Java

 Syntax: 

public elegance HashMap<Okay,V> extends AbstractMap<Okay,V> implements Map<Okay,V>, Cloneable, Serializable

Parameters: It takes two parameters specifically as follows:

  • The kind of keys maintained by means of this map (Okay)
  • The kind of mapped values (V)

For more info, consult with the thing – HashMap in Java with Examples

23. What are Assortment Interfaces?

The Assortment interface is a member of the Java Collections Framework. It is part of java.util bundle. It is among the root interfaces of the Assortment Hierarchy. The Assortment interface is indirectly carried out by means of any elegance. Alternatively, it’s carried out not directly by way of its subtypes or subinterfaces like Checklist, Queue, and Set. 

For Instance, the HashSet elegance implements the Set interface which is a subinterface of the Assortment interface. If a set implementation doesn’t put into effect a specific operation, it will have to outline the corresponding option to throw UnsupportedOperationException.

The Hierarchy of Assortment:

Collection Interface in Java

Assortment Interface in Java

24. Provide an explanation for the listing interface.

Class Interface in Java

Elegance Interface in Java

In Java, the Checklist interface lets in the person to retailer an ordered selection of items. The listing is the kid interface of Assortment. In Assortment, a listing is an ordered selection of items which will have reproduction values. Since Checklist preserves the insertion order, it lets in positional get right of entry to and insertion, which additionally lets in reproduction values.

Syntax:

public interface Checklist<E> extends Assortment<E> ;

This listing interface is carried out by means of more than a few categories like ArrayList, Vector, Stack, and many others. Since all of the subclasses put into effect the listing, we will instantiate a listing object with any of those categories. 

Instance: 

Checklist <T> al = new ArrayList<> (); 
Checklist <T> ll = new LinkedList<> (); 
Checklist <T> v = new Vector<> (); 

The place T is the kind of the thing 

Array List in Java

Array Checklist in Java

The categories which put into effect the Checklist interface are as follows:

  • ArrayList
  • LinkedList
  • Vector
  • Stack

25. Write a program to transform a given array into a set with the asList() way.

To transform array-based knowledge into Assortment founded we will use java.util.Arrays elegance. This elegance supplies a static way asList(T… a) that converts the array right into a Assortment.

Java

import java.util.*;

  

public elegance ArrayToCollection {

    public static void major(String args[])

    {

        

        String scholars[] = { "Kamlesh", "Abhay",

                              "Abhishek", "Shivansh" };

  

        

        Machine.out.println("Array enter: "

                           + Arrays.toString(scholars));

  

        

        

        Checklist studentList = Arrays.asList(scholars);

  

        

        Machine.out.println("Transformed components: "

                           + studentList);

    }

}

Output
Array enter: [Kamlesh, Abhay, Abhishek, Shivansh]
Transformed components: [Kamlesh, Abhay, Abhishek, Shivansh]

26. Differentiate between HashSet and HashMap

HashSet  HashMap 
HashSet implements the Set interface  HashMap implements the Map interface 
No Duplicates are allowed  Sure duplicates values are allowed however no reproduction secret is allowed 
Dummy values are allowed in HashSet. No Dummy values are allowed in HashMap.
A unmarried Object is needed all through an upload operation                                                  2 Items are required all through an upload operation
Pace is relatively slower than HashMap Pace is relatively sooner than HashSet as a result of hashing methodology has been used right here.
Have a unmarried null price  Unmarried null key and any choice of null values
Upload() way is used for the insertion The put () way is used for insertion.

For more info, consult with the thing – Distinction between HashMap and HashSet

27. Differentiate between HashSet and HashTable.

HashSet HashTable
HashSet lets in NULL Parts HashTable does now not permit NULL Parts.

Items that you simply insert in HashSet don’t seem to be assured to be inserted in the similar order. Items are inserted in response to their hash code. LinkedHashSet can be utilized to take care of order.

HashTable does now not take care of insertion order.
HashSet isn’t Synchronized however it may be synchronized externally. HashTable is Synchronized.
upload() way is used to insert into HashSet  put() way is used to insert into HashTable

28. What’s the default measurement of the burden issue within the hashing-based assortment?

Because the Load Issue will increase, the capability will increase in order that the operational complexity of the HashMap stays O(1) if the ratio of the present component to the preliminary capability crosses the edge. The which means of operational complexity of O(1) manner the retrieval and insertion operations take consistent time. The default load issue measurement is 0.75. The default capability is calculated by means of multiplying the preliminary capability by means of the burden issue.

For more info, consult with the thing – Load Think about HashMap in Java with Examples

29. What’s the distinction between Similar and Comparator in Java?

Java supplies two interfaces to kind items the usage of knowledge contributors of the category: 

Similar Comparator
The Similar interface supplies a unmarried sorting collection. The Comparator interface supplies more than one sorting sequences.
The real elegance is changed by means of a similar interface The real elegance isn’t changed by means of the Comparator interface.
compareTo() way is used to kind components. evaluate() way is used to kind components.
Similar is provide within the bundle java.lang Comparator is provide within the bundle java.util

For more info, consult with the thing – Similar vs Comparator in Java

30. What’s the distinction between fail-fast and failsafe?

Iterators in Java are used to iterate over the Assortment items. Fail-Rapid iterators right away throw ConcurrentModificationException if there’s a structural amendment of the gathering. Structural amendment manner including, or doing away with any component from a set whilst a thread is iterating over that assortment. Iterator on ArrayList and HashMap categories are some examples of fail-fast Iterator.

                                           Fail-Rapid                                                Fail-Protected
ConcurrentModificationException is thrown whilst editing the thing all through the iteration procedure. No Exception is thrown
Fail-Rapid wishes much less reminiscence all through the method. Fail-Protected iterator calls for extra reminiscence all through the method.                                                                    
A clone Object isn’t created all through the iteration procedure. A clone Object or a Reproduction is created all through the iteration procedure.
Fail-Rapid does now not permit amendment all through the method of iteration. Fail-Protected lets in amendment all through the method of iteration.
Fail-Rapid is immediate, Fail-Protected is somewhat slower than fail immediate.
Examples: ArrayList, Vector, HashMap, HashSet, and many others. Examples: ConcurrentHashMap, CopyOnWriteArrayList, and many others.

For more info, consult with the thing – Fail Rapid and Fail Protected Iterators in Java

31. Write a program to iterate the listing the usage of the lambda expression.

Iteration may also be finished the usage of a lambda expression.

Syntax:

list_name.forEach(variable->{//block of code})

Java

  

import java.util.*;

  

elegance GFG {

  

    

    public static void major(String args[])

    {

        

        Checklist<String> l = new ArrayList<String>();

  

        

        

        l.upload("Geeks");

        l.upload("for");

        l.upload("Geeks");

  

        

        l.forEach(

            (temp) -> { Machine.out.println(temp); });

    }

}

For more info, consult with the thing – Iterate via Checklist in Java

32. What’s IdentityHashMap?

The IdentityHashMap implements the Map interface the usage of Hashtable, evaluating keys (and values) the usage of reference equality as an alternative of object equality. This elegance implements the Map interface, however it deliberately breaks Map’s normal contract, which calls for that items are when put next the usage of the equals() way. This elegance is used when the person lets in items to be when put next the usage of references. It belongs to java.util bundle.

For more info, consult with the thing – IdentityHashMap elegance in Java

33. Write a program in Java to show the contents of a HashTable the usage of enumeration.

The hashtable elegance implements a hash desk, which maps keys to values. Any non-null object can be utilized as a key or as a worth. To effectively retailer and retrieve items from a hashtable, the items used as keys will have to put into effect the hashCode way and the equals way. Under is this system to show the contents of a HashTable the usage of enumeration:

Java

  

import java.io.*;

import java.util.Enumeration;

import java.util.Hashtable;

  

public elegance GFG {

  

    

    public static void major(String[] args)

    {

        

        Hashtable<Integer, String> hash

            = new Hashtable<Integer, String>();

  

        

        

        hash.put(1, "Geeks");

        hash.put(2, "for");

        hash.put(3, "Geeks");

  

        

        

        Enumeration e = hash.components();

  

        

        

  

        

        

        whilst (e.hasMoreElements()) {

  

            

            Machine.out.println(e.nextElement());

        }

    }

}

34. Write a program in java to get the gathering view of the values found in a HashMap.

Java’s HashMap elegance has the java.util.HashMap.values() way for developing collections out of HashMap values. It mainly returns a Assortment view of HashMap values.

Java

import java.util.*;

  

public elegance Hash_Map_Demo {

    public static void major(String[] args)

    {

  

        

        HashMap<Integer, String> hash_map

            = new HashMap<Integer, String>();

  

        

        hash_map.put(0, "Welcome");

        hash_map.put(1, "to");

        hash_map.put(2, "Geeks");

        hash_map.put(3, "4");

        hash_map.put(4, "Geeks");

  

        

        Machine.out.println("Preliminary Mappings are: "

                           + hash_map);

  

        

        Machine.out.println("The gathering is: "

                           + hash_map.values());

    }

}

Output
Preliminary Mappings are: {0=Welcome, 1=to, 2=Geeks, 3=4, 4=Geeks}
The gathering is: [Welcome, to, Geeks, 4, Geeks]

For more info, consult with the thing – HashMap values() Approach in Java

35. Write a program to sign up for two ArrayList into one unmarried ArrayList.

Given two ArrayLists in Java, our activity is to sign up for those ArrayLists.

Java

  

import java.util.*;

  

public elegance GFG {

    public static void major(String args[])

    {

  

        ArrayList<String> list_1 = new ArrayList<String>();

  

        list_1.upload("Geeks");

        list_1.upload("For");

        list_1.upload("ForGeeks");

  

        

        Machine.out.println("ArrayList 1: " + list_1);

  

        ArrayList<String> list_2 = new ArrayList<String>();

  

        list_2.upload("GeeksForGeeks");

        list_2.upload("A pc portal");

  

        

        Machine.out.println("ArrayList 2: " + list_2);

  

        

        

        list_1.addAll(list_2);

  

        

        Machine.out.println("Joined ArrayLists: " + list_1);

    }

}

Output
ArrayList 1: [Geeks, For, ForGeeks]
ArrayList 2: [GeeksForGeeks, A computer portal]
Joined ArrayLists: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]

For more info, consult with the thing – Sign up for two ArrayLists in Java

36. How are you able to synchronize an ArrayList in Java?

The usage of the Collections.synchronizedList() way, we will synchronize our collections in Java. SynchronizedList() returns a synchronized (thread-safe) listing sponsored by means of a variety.

Java

import java.io.*;

import java.util.*;

  

elegance GFG {

    public static void major(String[] args)

    {

        

        Checklist<String> listing = new ArrayList<String>();

  

        listing.upload("Consume");

        listing.upload("Espresso");

        listing.upload("Code");

        listing.upload("Sleep");

        listing.upload("Repeat");

  

        

        listing = Collections.synchronizedList(listing);

  

        

        

        synchronized (listing)

        {

            Iterator<String> it = listing.iterator();

            whilst (it.hasNext()) {

                Machine.out.println(it.subsequent());

            }

        }

    }

}

Output
Consume
Espresso
Code
Sleep
Repeat

37. What’s a Houses Elegance in Java? 

The homes elegance is a subclass of Hashtable. The homes elegance shops a listing of values whose secret is a string and whose price could also be a string. Houses can outline different homes elegance lists, however the default is homes.

Options of Houses elegance:

  • Belongings is a subclass of Hashtable.
  • The Houses document is used to retailer and retrieve string knowledge kind for a listing of values the place the secret is a string and the price could also be a string.
  • If the unique homes listing does now not comprise a definite key belongings, the default homes listing will probably be searched as an alternative.
  • Items may also be shared by means of more than one threads with out exterior synchronization.
  • The homes elegance can be utilized to retrieve the homes of the machine.

For more info, consult with the thing – Houses Elegance in Java

38. What is going to occur should you use HashMap in a multithreaded Java utility?

In a multi-threaded surroundings, if more than one threads modify the map structurally, akin to including, doing away with, or editing mappings, the interior knowledge construction of HashMap would possibly develop into corrupted and there is also some lacking hyperlinks, fallacious entries, and the map itself would possibly develop into utterly needless. Thus, you will have to now not use HashMap in a concurrent utility; as an alternative, use ConcurrentHashMap or Hashtable which is thread-safe. The ConcurrentHashMap contains all of the Hashtable’s strategies in addition to complete concurrency of retrievals and updates.

How did ThreadSafeConcurrentHashMap develop into thread-safe? 

  • java.util.Concurrent.ConcurrentHashMap elegance supplies thread protection by means of dividing the map into segments, which permits the lock to be taken solely as soon as consistent with section, i.e, as soon as for every single thread.
  • The learn operation in ConcurrentHashMap does now not require a lock. 

For more info, consult with the thing – How Does ConcurrentHashMap Reach Thread-Protection in Java?

39. What is going to occur if two other keys of HashMap go back the similar hashcode()?

When two other keys of HashMap go back the similar hash code, they’ll finally end up in the similar bucket; due to this fact, collisions will happen. n case of collision, i.e. index of 2 or extra nodes is similar, nodes are joined by means of a hyperlink listing i.e. the second one node is referenced by means of the primary node and the 3rd by means of the second one, and so forth.

For more info, consult with the thing – Inner Running of HashMap in Java

40. What’s WeakHashMap?

WeakHashMap implements the Map interface. In contrast to HashMap, WeakHashMap lets in rubbish assortment even though the thing specified as the foremost doesn’t comprise any references in spite of being related to WeakHashMap. In different phrases, Rubbish Collector is healthier than WeakHashMap.

For more info, consult with the thing – Hashmap vs WeakHashMap in Java

41. What’s UnsupportedOperationException?

Within the context of APIs or listing implementations, the UnsupportedOperationException is a commonplace exception. The exception is thrown when the asked operation can’t be carried out. This elegance is a member of the Java Collections Framework.

Syntax:

public elegance UnsupportedOperationException
extends RuntimeException

For more info, consult with the thing – UnsupportedOperationException

42. Find out how to make a Assortment Learn-Simplest in Java?

Making a Learn-Simplest Assortment comes to limiting the thing to just fetching the knowledge and now not including or doing away with knowledge. Java has other strategies for various Assortment sorts like unmodifiableCollection(), unmodifiableMap(), ununmodifiableSet(), and many others. java.util.The collections elegance defines all strategies. The unmodifiableCollection() way creates a Learn-Simplest assortment. It calls for a connection with the Assortment elegance. If we’ve got an object of Set Interface, we will use ununmodifiableSet() to make Learn-Simplest.

For more info, consult with the thing – Find out how to Make a Assortment Learn-Simplest in Java?

43. Distinction between PriorityQueue and TreeSet in Java? 

                   PriorityQueue

                                TreeSet

PriorityQueue is available in JDK 1.5. TreeSet is available in JDK 1.4.
The knowledge construction utilized by PriorityQueue is Queue The knowledge construction utilized by TreeSet is Set.
Reproduction components are allowed. Reproduction components don’t seem to be allowed.
Excluding for the foundation component, the remainder of the weather don’t practice any specific order in PriorityQueue. In TreeSet all of the components stay within the taken care of order.
The usage of PriorityQueue, we will retrieve the most important or smallest component in O(1) time. TreeSet doesn’t supply a method to retrieve the most important or smallest component in O(1) time, however since they’re in taken care of order it will get the primary or final component in O(1) time.

For more info, consult with the thing – Distinction Between PriorityQueue and TreeSet

44. What’s the diamond operator in Java?

Diamond operators are used for simplifying using generics when developing items whilst warding off unchecked warnings in a program. When the Diamond operator was once offered in Java 7, we will create the thing with out citing the generic kind at the proper facet of the expression as proven under.

Syntax:

Checklist<String> listing = new ArrayList<>();

For more info, consult with the thing – Diamond operator

45. How TreeMap works in Java?

TreeMap shops the key-value pairs, however TreeMap types the keys ascending relatively than descending like HashMap. Relying on which constructor is used, TreeMap will probably be taken care of both in response to its keys, or by means of a Comparator. In TreeMap, the weather are taken care of in response to a Purple-Black tree. A red-black tree is a self-balancing binary seek tree the place every single node has an additional bit, and that bit is regularly interpreted as the colour (purple or black). Those colours are used to be sure that the tree stays balanced all through insertions and deletions. 

Structure of a Node in Java

Construction of a Node in Java

For more info, consult with the thing – Inner Running of TreeMap in Java

46. Checklist down techniques to iterate over Map in java?

The HashMap elegance supplies Java’s Map interface by means of storing knowledge in (Key, Worth) pairs and getting access to them by means of an index of every other kind. To make use of this elegance it is crucial to import java.util.HashMap bundle or its superclass.

There are a lot of techniques to iterate over HashMap of which 5 are indexed under:

  1. Iterate via a HashMap EntrySet the usage of Iterators.
  2. Iterate via HashMap KeySet the usage of Iterator.
  3. Iterate HashMap the usage of for-each loop.
  4. Iterating via a HashMap the usage of Lambda Expressions.
  5. Loop via a HashMap the usage of Circulate API.

For more info, consult with the thing – Find out how to Iterate HashMap in Java

47. What’s CopyOnWriteArrayList in Java?

CopyOnWriteArrayList in Java

CopyOnWriteArrayList in Java

JDK 1.5 offered an enhanced model of ArrayList referred to as CopyOnWriteArrayList, the place all changes (upload, set, take away, and many others) are carried out by means of a brand new reproduction. It may be present in java.util.concurrent. This is a knowledge construction created for use in a concurrent surroundings. In a Thread-based surroundings, the CopyOnWriteArrayList is meant for common studying and rare updating. CopyOnWriteArrayList is a thread-safe model of  ArrayList.

For more info, consult with the thing – CopyOnWriteArrayList in Java

48.  What’s EnumMap in Java?

EnumMap is an implementation of the Map interface explicit to enumeration sorts. EnumMap elegance is a member of the Java Collections Framework & isn’t synchronized. It extends AbstractMap and implements the Map interface in java. EnumMap belongs to java.util bundle.

Syntax: 

public elegance EnumMap<Okay extends Enum<Okay>,​V> extends AbstractMap<Okay,​V> implements Serializable, Cloneable

// Okay will have to lengthen Enum, which enforces the requirement that the keys will have to be of the desired enum kind. 

Parameters:

  • Key object kind
  • Worth object kind
EnumMap in Java

EnumMap in Java

For more info, consult with the thing – EnumMap elegance in Java

49. How does Hashmap internally Works?

HashMap works at the theory of Hashing. HashMap accommodates an array of Node and Node can constitute a category having the next items:

  • int hash
  • Okay key
  • V price
  • Node subsequent

The inner workings of HashMap:

  • Hashing
  • Buckets
  • Index Calculation in Hashmap

For more info, consult with the thing – Inner Running of HashMap in Java

50. Why iterator in hashmap is regarded as fail-fast?

fail-fast iterators right away throw concurrent amendment exceptions if any thread from outdoor makes an attempt to switch the gathering on which they’re iterating. The fail-fast characteristic guarantees that the iterator fails right away if it detects that any amendment of the gathering will result in anomalous habits at some point.

Fail immediate characteristic guarantees that if iterator feels that amendment of assortment would lead to anamolous behaviour at any level of time in long run, it fails right away.

Instance:

Java

  

import java.io.*;

import java.util.ArrayList;

import java.util.Iterator;

  

public elegance GFG {

    public static void major(String[] args)

    {

        ArrayList<Integer> arr = new ArrayList<>();

        arr.upload(1);

        arr.upload(2);

        arr.upload(3);

        arr.upload(4);

        arr.upload(5);

  

        Iterator<Integer> it = arr.iterator();

        whilst (it.hasNext()) {

            if (it.subsequent() == 2) {

                

                it.take away();

            }

        }

  

        Machine.out.println(arr);

  

        it = arr.iterator();

        whilst (it.hasNext()) {

            if (it.subsequent() == 3) {

                

                

                arr.take away(3);

            }

        }

    }

}

Output:

[1, 3, 4, 5]
Exception in thread "major" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.subsequent(ArrayList.java:851)
    at FailFastExample.major(FailFastExample.java:28)

For more info, consult with the thing – Fail Rapid and Fail Protected Iterators in Java

FAQs

1. What’s collections in Java interview questions?

Assortment in Java is a framework used for storing and manipulating collections of items.

2. What are the 4 assortment categories in Java?

There are lots of collections in Java however out of them maximum used collections are:

  1. ArrayList
  2. LinkedList
  3. HashSet
  4. Stack

3. Can HashMap have reproduction keys?

No, HashMap can’t have reproduction keys. As HashMap is among the collections in Java, it shops the price within the type of key-value and each and every key has its personal price hooked up to it. So, as no key will have two price manner we will’t have reproduction keys in HashMap.

4. Why array isn’t a set?

The array isn’t a set, it’s all as a result of the adaptation within the capability between collections and arrays few of which can be discussed under:

  • The dimensions of the Array can’t be modified as soon as declared
  • Arrays can dangle solely homogeneous knowledge sorts components.
  • The array can dangle each primitive datatypes and items while in collections it is just ready to carry wrapper items.

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: