Technical Interview Questions on Java Collections
- What exactly does the Java Collection framework do?
Answer) To store and modify data in the form of objects, the Collection Framework, a combination of classes and interfaces, is employed. For this reason, it offers a variety of classes and interfaces, including ArrayList, Vector, Stack, and HashSet, among others.
- What are the primary distinctions between an array and a collection?
Answer) Although they have certain similarities when it comes to handling and storing object references, arrays and collections are very different from one another. Here are the key distinctions between an array and a collection:
In contrast to collections, where size can be adjusted dynamically as needed, arrays are always of a fixed size, meaning that a user cannot alter the length of an array to meet their needs or at runtime.
Collections allow the storage of heterogeneous objects, as contrast to Arrays which may only store objects of the same kind.
Collections contain preconfigured methods that can be used for user requirements like sorting, searching, etc. that Arrays cannot.
- The interface for the collection is expanded by the List and Set. The following list of distinctions between the two, nonetheless, is not exhaustive.
Answer) While Set has unique objects, List can have duplicate pieces.
In contrast to the unordered Set collection, which does not retain insertion order, the List is an ordered collection that does.
The only legacy class in the List interface is the Vector class, while the Set interface lacks any legacy classes.
Unlike the Set interface, which only permits one null value, the List interface supports an unlimited number of null values.
- Describe how Java supports linked lists.
Answer) Java supports the following two forms of linked lists:
One-way linked list: Data structures include singly linked lists. Each node in a singly linked list keeps a reference to the node after it in the list, as well as the contents of that node. There are no references or pointers to the preceding node stored there.
doppelganger lists: Unlike other types of linked lists, doubly linked lists allow traversal of the data items in both directions. Every node contains two links—one that connects to the node after it and another that links to the node before it—which makes this possible.
- What is the Properties file’s major advantage?
Answer) The key benefit of using a properties file in Java is that any changes to those values are automatically reflected in the Java class without the need to recompile it. As a result, it mostly serves to store information that is subject to change, including usernames and passwords. This facilitates simple and effective application management. Here is an illustration of the same:
import java.util.*;
import java.io.*;
public class PropertiesDemo{
public static void main(String[] args)throws Exception{
FileReader fr=new FileReader(“db.properties”);
Properties pr=new Properties();
pr.load(fr);
System.out.println(pr.getProperty(“user”));
System.out.println(pr.getProperty(“password”));
}
}
- What does the Java Collection Framework’s term “Iterator” mean?
Answer) An interface of the Collection framework found in the java.util package is known as an iterator in Java. Iterating through a group of items in Java is done using a Cursor. The Iterator interface also offers the following other key features:
Explore a group of object elements one by one.
Because it applies to all Collection foundation classes, it is known as the “Universal Java Cursor.”
READ and REMOVE operations are supported.
Iterator method names are simple to use.
- Why is it necessary to override Java’s equals() method?
Answer) Checking if two objects are identical or not is made easier with the equals method’s original implementation. However, you will need to override this method if you want to compare the objects according to the property.
- How does Java arrange collection objects?
Answer) Java Collections’ Comparable and Comparator interfaces are used to implement sorting. When the Collections.sort() function is used, the compareTo() method’s supplied natural order is used to sort the elements. However, when the Collections.sort(Comparator) method is used, the objects are sorted according to the compare() method of the Comparator interface.
- Why is the List interface used?
Answer) An ordered group of components makes up the List interface in Java. Duplicate values may be kept there while the insertion order is preserved. The many methods in this interface provide for easy element modification based on the element index. ArrayList, LinkedList, Stack, and Vector are the primary classes that implement the List interface of the Collection framework.
- What distinguishes the hashset and hashmap algorithms?
Answer) The following is a list of the differences between the HashSet and HashMap.
While HashMap also contains entries, HashSet simply contains values (key, value). Although HashMap must be converted into Set in order to be iterated, HashSet can be.
When compared to HashMap, HashSet implements the Set interface.
While HashSet cannot include any duplicate values, HashMap can have duplicate values when the keys are different.
HashSet only includes a single null value, whereas HashMap can store a single null key with an unlimited number of null values.
- How do you change an array into an array list and an array into an array list?
Answer) Utilizing the asList() method that the Array class offers allows an Array to be transformed into an ArrayList. List objects may be passed as a parameter to this static function.
Syntax:
Arrays.asList(item)
While the toArray() function of the ArrayList class allows an ArrayList to be transformed into an Array.
Syntax:
List_object.toArray(new String[List_object.size()])
- How can a list be turned around?
Answer) The reverse() function of the Collections class can be used to reverse an ArrayList.
Syntax:
public static void reverse(Collection c)
For Example:
public class ReversingArrayList {
public static void main(String[] args) {
List<String> myList = new ArrayList<String>();
myList.add(“AWS”);
myList.add(“Java”);
myList.add(“Python”);
myList .add(“Blockchain”);
System.out.println(“Before Reversing”);
System.out.println(myList.toString());
Collections.reverse(myList);
System.out.println(“After Reversing”);
System.out.println(myList);
}
}
- What distinguishes a collection from a collection of collections?
Answer) Below is a list of the variations between the Collection and Collections.
In contrast to Collections, which is a class, the Collection is an interface.
List, Set, and Queue are all given access to the Collection interface’s standard data structure functionality. Collections class is responsible for sorting and synchronizing the collection’s items, nevertheless.
The Collection interface offers data structure-specific methods, whereas the Collections class offers static methods that may be used for a variety of operations on a collection.
- What do you mean when you say blocking queue?
Answer) The Queue interface is extended by the BlockingQueue interface. It allows for concurrent retrieval, insertion, and delete operations. In order to retrieve any element, it waits for the queue to not be empty. It waits for a space to open up while storing the elements. The implementation of BlockingQueue is thread-safe and it cannot contain null entries.
Syntax:
public interface BlockingQueue<E> extends Queue <E>
- What benefits do Properties files offer?
Answer) You do not need to recompile the Java class if the value in the properties file is changed. This makes it simple to manage the application. It is used to hold data that will be updated often. Think about the case below.
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
FileReader reader=new FileReader(“db.properties”);
Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperty(“user”));
System.out.println(p.getProperty(“password”));
}
}
Output
system
oracle
- List the advantages of the generic collection.
Answer) The following are advantages of utilizing the generic collection:
There is no need for typecasting if the programmers are using generic classes.
It is type-safe and may be verified during compilation.
By finding bugs during compilation, it ensures that the code is stable.
- What in Java is a priority queue?
Answer) Java’s equivalent of a regular queue or stack data structure is an abstract data type called a priority queue. However, each element of a priority queue has a unique property called priority. Regardless of their insertion order, a high priority element in this queue is served before a low priority element. On the priority heap, the PriorityQueue is based. The components of the priority queue are organized depending on the function Object() { [native code] } used, the queue can be ordered naturally or using a Comparator that is provided at the time of queue building.
- What exactly is Java’s HashSet class and how does it store elements?
Answer) The Java collections framework’s HashSet class, which implements the Set interface and derives from AbstractSet, is a member. It creates and stores a collection of unique elements by indirectly implementing a hashtable. An instance of the HashMap class called a hashtable employs a hashing algorithm to store data in a hash set. Informational content is transformed into a distinctive value, more commonly referred to as a hash code, through the process of hashing. Following that, the data linked to the key is indexed using this hashcode. The whole conversion of the informative key into the hashcode is carried out inside.
- A TreeSet or HashSet can both contain null elements.
Only one null element can be added to a HashSet, but since TreeSet uses NavigableMap to store its elements, it is not possible to add any null items to it. This is so because the NavigableMap is a SortedMap subtype that forbids null keys. Therefore, a TreeSet will produce a NullPointerException if you attempt to add null elements to it.
- What does the Collections framework’s emptySet() method do?
Its collections.
The empty immutable Set is returned using the emptySet() method while the null entries are removed. This method returns a set that can be serialized. The declaration of emptySet’s method is seen below ().
Syntax:
public static final <T> Set<T> emptySet()
- Give an illustration of how to order an array in ascending order.
Answer) Here’s an illustration of how to sort an array in ascending order:
package com.seven;
public class SelectionSortAlgo {
public static void main(String a[])
{
int[] myArray = {860,8,200,9};
System.out.println(“——Before Sort—–“);
printArray(myArray);
selection(myArray);//sorting array using selection sort
System.out.println(“—–After Sort—–“);
printArray(myArray);
}
public static void selection(int[] array)
{
for (int i = 0; i < array.length – 1; i++)
{ System.out.println(“Sort Pass Number “+(i+1));
int index = i;
for (int j = i + 1; j < array.length; j++)
{
System.out.println(“Comparing “+ array[index] + ” and ” + array[j]);
if (array[j] < array[index]){
System.out.println(array[index] + ” is greater than ” + array[j] );
index = j;
}
}
int smallerNumber = array[index];
array[index] = array[i];
array[i] = smallerNumber;
System.out.println(“Swapping Elements: New Array After Swap”);
printArray(array);
}
}
static void printArray(int[] array){
for(int i=0; i < array.length; i++)
{
System.out.print(array[i] + ” “);
}
System.out.println();
}
}
- What in Java is the Map interface?
Answer) The Java.util package is used to perform various operations on Java.
Java’s map interface saves the items as pairs of keys and values to allow for quicker lookups. Each key in this case uniquely corresponds to a single value. The term “map entries” refers to these key-value pairs. This interface has method signatures for adding, deleting, and retrieving components using a key. The usage of dictionaries for key-value association mapping is ideal with such methods.
- Why is the Collection Interface not extended by Map?
Answer) The Collection interface in Java is a collection of objects that are stored in a structured manner with a designated access mechanism, as opposed to the Map interface in Java which follows a key/value pair structure. Because the Collection interface’s add(E e) function does not handle key-value pairs like the Map interface’s put. (K, V) method does, Map does not extend the Collection interface. It may not extend the Collection interface, but it is nonetheless a crucial component of the Java Collections framework.
- How many different Collection views are offered by the Map interface in the Java Collection framework?
Answer) The Map interface has three different key-value pair views: key set view, value set view, and entry set view.
The iterators make it simple to move between all of these views.
- What are the advantages of Java’s Collection Framework?
Answer) The advantages of Java’s Collection Framework are:
The Java collection framework provides extremely effective data structures that improve the program’s precision and speed.
It is simple to maintain an application created using the Java collection framework.
The reusability of code can be increased by a developer by combining classes with other types.
Programmers can change the primitive collection types however they want thanks to the Java collection framework.
- In Java, describe Vector
Answer) An array and a vector are the same thing. It has elements that are reachable via an index value. A legacy method that is not a part of the collection framework may be found in vectors.
- Can any class be used as a Map key?
Answer) Any class may be used as a map key if the following factors are taken into account:
Equals() and hashCode() methods must both be overridden by the class.
The equals() and hashCode() rules should be followed by the class in all circumstances.
The HashCode() method shouldn’t use the class field if the equals() method doesn’t use it either.
A user-defined key class should be made immutable for optimal usage.
- Create an EnumSet java.util file.
Answer) An implementation of Set called EnumSet can be utilized with enum types. A single enum type must be supplied explicitly or implicitly for an enumSet to contain all of its components. Additionally, null keys are not permitted, nor is it synchronized. EnumSet has operations such as copyOf, complementOf(EnumSet s), and EnumSetof(E first, E… rest) (Collection c).
- In an ArrayList, how can duplicates be removed in two different ways?
Answer) Duplicates in an ArrayList can be eliminated in two ways:
Developers can utilize hash sets to eliminate redundant elements from array lists. Its inability to maintain insertion order is a negative.
LinkedHashSet: As an alternative to HashSet, developers can also preserve the order of insertion by using LinkedHashSet.
- Describe IdentityHashMap.
The class IdentityHashMap extends the AbstractMap class and implements the Serializable and Cloneable interfaces. It’s made for situations where reference-equality semantics are required.
- Describe WeakHashMap.
A Java Map implementation is called WeakHashMap. Weak references to the keys are stored there. A key-value pair can be collected as garbage while sorting using this Map. Outside of WeakHashMap, its key is not referred to.
- How can you make a collection thread-safe?
Collection thread security can be achieved using the following techniques:
Collections.synchronizedList(list);
Collections.synchronizedMap(map);Collections.synchronizedSet(set);
33) Do you implement Java’s ConcurrentHashMap? What does it do?
Answer) Java class ConcurrentHashMap implements the ConcurrentMap and Serializable interfaces. Since HashMap doesn’t function well in a multithreaded context, this class is an improved version of it. Compared to HashMap, it performs more efficiently.
A brief illustration of ConcurrentHashMap’s implementation is provided below:
package seven;
import java.util.concurrent.*;
public class ConcurrentHashMapDemo {
public static void main(String[] args)
{
ConcurrentHashMap m = new ConcurrentHashMap();
m.put(1, “Welcome”);
m.put(2, “to”);
m.put(3, “Seven”);
m.put(4, “Demo”);
System.out.println(m);
// Here we cant add Hello because 101 key
// is already present in ConcurrentHashMap object
m.putIfAbsent(3, “Online”);
System.out.println(“Checking if key 3 is already present in the ConcurrentHashMap object: “+ m);
// We can remove entry because 101 key
// is associated with For value
m.remove(1, “Welcome”);
System.out.println(“Removing the value of key 1: “+m);
// Now we can add Hello
m.putIfAbsent(1, “Hello”);
System.out.println(“Adding new value to the key 1: “+m);
// We can’t replace Hello with For
m.replace(1, “Hello”, “Welcome”);
System.out.println(“Replacing value of key 1 with Welcome: “+ m);
}
}
- Which collection in Java is quicker?
Answer) ArrayList should be your first choice if you require quick access to elements using an index. Use HashMap to quickly access components using a key. Use LinkedList if you require quick addition and removal of entries (but it has a very poor seeking performance).
- What collection is the most popular in Java?
Answer) The Java Collections Framework offers a number of universal implementations of the fundamental interfaces: The most popular implementation of the Set interface is HashSet. The most popular implementation of the List interface is an array list.
- Which collection lends itself most to sorting?
Answer) Use any type of List and Collections to sort a list if that’s all you want to do. sort(). Use a SortedSet to guarantee that the list’s elements are always sorted and unique.
- ArrayList vs HashSet: which is quicker?
Answer) Conclusion: Compared to an ArrayList, the HashSet contains() method performs more quickly.
- What distinguishes Java’s hashtable from its hashmap?
Answer) There are numerous differences between them, but the most crucial one is thread safety; HashMap is not thread-safe, but Hashtable is thread safe collection.
- What does CopyOnWriteArrayList mean?
Answer) The add and set actions are carried out by making a duplicate of the array in the CopyOnWriteArrayList form of the ArrayList. It doesn’t throw ConcurrentModificationException because it is a thread-safe program. Any element, even null, is allowed in this ArrayList.
- The Java Queue interface’s list of available methods
- added boolean (object)
- Boolean offering (object)
- object remove(), object poll, object element, and object peek ()
- With examples, describe each loop.
Answer) An alternative for loop that is used to go through the array is the for-each loop. Since the loop doesn’t use the index or rather the counter, the amount of code is greatly reduced.
a case of a for each loop is:
class UsingForEach {
public static void main(String[] args) {
String[] arrData = {“Alpha”, “Beta”, “Gamma”, “Delta”, “Sigma”};
//The conventional approach of using the for loop
System.out.println(“Using conventional For Loop:”);
for(int i=0; i< arrData.length; i++){
System.out.println(arrData[i]);
}
System.out.println(“\nUsing Foreach loop:”);
//The optimized method of using the for loop – also called the foreach loop
for (String strTemp : arrData){
System.out.println(strTemp);
}
}
}