Docsity

80 Java Collections Interview Questions and Answers, Summaries of Computer Science

Toggle sidebar
bg1
80 Java Collections Interview Questions and Answers
(2022)
Here are Java Collections Interview Questions for fresher as well as experienced candidates to get their
dream job.
1) What is framework in Java?
A framework is a popular and readymade architecture that contains a set of classes and interfaces.
2) What is the Collection framework in Java?
Collection Framework is a grouping of classes and interfaces that is used to store and manage the objects.
It provides various classes like Vector, ArrayList, HashSet, Stack, etc. Java Collection framework can also
be used for interfaces like Queue, Set, List, etc.
3) Explain Collections Class
java.util.Collections is a class consists of static methods that operate on collections. It contains polymorphic
algorithms to operate on collections, “wrappers”. This class contains methods for algorithms, like binary
sorting, search, shuffling, etc.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c

Partial preview of the text

Download 80 Java Collections Interview Questions and Answers and more Summaries Computer Science in PDF only on Docsity!

80 Java Collections Interview Questions and Answers

Here are Java Collections Interview Questions for fresher as well as experienced candidates to get their

dream job.

1) What is framework in Java?

A framework is a popular and readymade architecture that contains a set of classes and interfaces.

2) What is the Collection framework in Java?

Collection Framework is a grouping of classes and interfaces that is used to store and manage the objects.

It provides various classes like Vector, ArrayList, HashSet, Stack, etc. Java Collection framework can also

be used for interfaces like Queue, Set, List, etc.

3) Explain Collections Class

java.util.Collections is a class consists of static methods that operate on collections. It contains polymorphic

algorithms to operate on collections, “wrappers”. This class contains methods for algorithms, like binary

sorting, search, shuffling, etc.

4) What is the hashCode()?

The hashCode() is a method that returns an integer hash code.

EXPLORE MORE Learn Java Programming with Beginners Tutorial08:32 Linux Tutorial for

Beginners: Introduction to Linux Operating...01:35 What is Integration Testing Software Testing

Tutorial03:04 What is JVM (Java Virtual Machine) with Architecture JAVA...02:24 How to write a

TEST CASE Software Testing Tutorial01:08 Seven Testing Principles Software Testing05:01 Linux

File Permissions Commands with Examples13:29 How to use Text tool in Photoshop CC Tutorial08:

What is NoSQL Database Tutorial02:00 Important Linux Commands for Beginners Linux

Tutorial15:

5) Distinguish between ArrayList and Vector in the Java collection framework. ArrayList Vector ArrayList is cannot be synchronized. Vector can be is synchronized. It is not a legacy class. It is a legacy class. It can increase its size by 50% of the size of the array. It can increase its size by doubling the size of the array. ArrayList is not thread-safe. Vector is a thread-safe. 6) What is ArrayList in Java?

ArrayList is a data structure that can be stretched to accommodate additional elements within itself and

shrink back to a smaller size when elements are removed. It is a very important data structure useful in

handling the dynamic behavior of elements.

The syntax of BlockingQueue is:

public interface BlockingQueue extends Queue 10) Explain override equals() method

The equals method is used to check the similarity between two objects. In case if the programmer wants to

check an object based on the property, then it needs to be overridden.

11) What is the difference between Comparable and Comparator?

The difference between Comparable and Comparator is:

Comparable Comparator Comparable provides compareTo() method to sort elements in Java. Comparator provides compare() method to sort elements in Java. Comparable interface is present in java.lang package. Comparator interface is present in java. util package. The logic of sorting must be in the same class whose object you are going to sort. The logic of sorting should be in a separate class to write different sorting based on different attributes of objects. The class whose objects you want to sort must implement the comparable interface. Class, whose objects you want to sort, do not need to implement a comparator interface. It provides single sorting sequences. It provides multiple sorting sequences. This method can sort the data according to the natural sorting order. This method sorts the data according to the customized sorting order. It affects the original class. i.e., the actual class is altered. It doesn’t affect the original class, i.e., the actual class is not altered. Implemented frequently in the API by Calendar, Wrapper classes, Date, and String. It is implemented to sort instances of third-party classes. All wrapper classes and String class implement the comparable interface. The only implemented classes of Comparator are Collator and RuleBasedColator.

12) Explain equals() with example

Equals() verifies whether the number object is equal to the object, which is passed as an argument or not.

The syntax of the equals() method is:

public boolean equals(Object o)

This method takes two parameters 1) any object, 2) return value. It returns true if the passed argument is not

null and is an object of a similar type having the same numeric value.

Example:

import java.lang.Integer; public class Test { public static void main(String args[]) { Integer p = 5; Integer q = 20; Integer r =5; Short s = 5; System.out.println(p.equals(q)); System.out.println(p.equals(r)); System.out.println(p.equals(s)); } } 13) List out benefits of generic collection

The benefits of using the generic collection are:

 If the programmers are using generic class, they don’t require typecasting.

 It is type-safe and can be checked at the time of compilation.

 It provides the stability of the code by detecting bug at the compilation time.

//Remove element by index arlTest.remove(2); System.out.println("See contents after removing element by index: " + arlTest); //Check size after removing elements System.out.println("Size of arrayList after removing elements: " + arlTest.size()); System.out.println("List of all elements after removing elements: " + arlTest); //Check if the list contains "K" System.out.println(arlTest.contains("K")); } } 16) Give example to sort an array in dscending order

The example of sort an array in decending order is:

package com.guru99; 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(); } } 17) Explain the basic interfaces of the Java collections framework

Java collection framework is a root of the collection hierarchy. It represents a group of objects as its

elements. The Java programming language does not provide a direct implementation of such interface.

 Set: Set is a collection having no duplicate elements. It uses hashtable for storing elements.

 List: List is an ordered collection that can contain duplicate elements. It enables developers to access

any elements from its inbox. The list is like an array having a dynamic length.

 MAP: It is an object which maps keys to values. It cannot contain duplicate keys. Each key can be

mapped to at least one value.

A stack is a special area of computer’s memory that stores temporary variables created by a function. In

stack, variables are declared, stored, and initialized during runtime.

20) What is linked list?

A linked list is a data structure that can store a collection of items. In other words, linked lists can be utilized

to store several objects of the same type. Each unit or element of the list is referred as a node. A node in the

Linked list has its data and the address of the next node. It is like a chain. Linked Lists are used to create

graphs and trees.

21) Give example of ArrayList

The example of ArrayList is:

import java.util.ArrayList; class Test_ArrayList { public static void main(String[] args) { //Creating a generic ArrayList ArrayList arlTest = new ArrayList(); //Size of arrayList System.out.println("Size of ArrayList at creation: " + arlTest.size()); //Lets add some elements to it arlTest.add("D"); arlTest.add("U"); arlTest.add("K"); arlTest.add("E"); //Recheck the size after adding elements System.out.println("Size of ArrayList after adding elements: " + arlTest.size()); //Display all contents of ArrayList System.out.println("List of all elements: " + arlTest); //Remove some elements from the list

arlTest.remove("D"); System.out.println("See contents after removing one element: " + arlTest); //Remove element by index arlTest.remove(2); System.out.println("See contents after removing element by index: " + arlTest); //Check size after removing elements System.out.println("Size of arrayList after removing elements: " + arlTest.size()); System.out.println("List of all elements after removing elements: " + arlTest); //Check if the list contains "K" System.out.println(arlTest.contains("K")); } } 22) Explain linked list supported by Java

Two types of linked list supported by Java are:

 Singly Linked list: Singly Linked list is a type of data structure. In a singly linked list, each node in the

list stores the contents of the node and a reference or pointer to the next node in the list. It does not

store any reference or pointer to the previous node.

 Doubly linked lists: Doubly linked lists are a special type of linked list wherein traversal across the

data elements can be done in both directions. This is made possible by having two links in every node,

one that links to the next node and another one that connects to the previous node.

23) Explain the methods provided by the Queue interface?

Methods of Java Queue interface are:

Method Description boolean add(object) Inserts specified element into the Queue. It returns true in case it a success.

Collection Collections The collection is an interface. Collections is a class. It represents a group of objects as a single entity. It defines various utility methods for collection objects. The collection is the root interface of the Java Collection framework. Collections is a general utility class. This interface is used to derive the collection data structures. This class contains static methods to manipulate data structure. 27) Define LinkedHashSet in the Java Collection framework?

LinkedHashSet is a subclass of the class called HashSet and implements the set interface. It is a well-

ordered version of HashSet that maintains a doubly-linked List across its all elements.

28) What is the difference between failfast and failsafe? Failfast Failsafe It does not allow collection modification while iterating. It allows collection modification while iterating. It can throw ConcurrentModificationException It can’t throw any exception. It uses the original collection to traverse the elements. It uses an original collection copy to traverse the elements. There is no requirement of extra memory. There is a requirement of extra memory. 29) List collection views of a map interface

Collection views of map interface are: 1) key set view, 2) value set view, and 3) entry set view.

30) What are the benefits of the Collection Framework in Java?

The benefits of Collection Framework in Java are:

 Java collection framework offers highly efficient and effective data structures that enhance the

accuracy and speed of the program.

 The program developed with the Java collection framework is easy to maintain.

 A developer can mix classes with other types that result in increasing the reusability of code.

 The Java collection framework enables programmers to modify the primitive collection types the way

they like.

31) What is a good way to sort the Collection objects in Java?

A good way to sort Java collection objects is using Comparable and Comparator interfaces. A developer can

use Collections.sort(), the elements are sorted based on the order mention in compareTo().

When a developer uses Collections, sort (Comparator), it sorts the objects depend on compare() of the

Comparator interface.

32) Explain Vector in Java

The vector is the same as an array. It has components that can be accessed using an index value. Vectors

can contain a legacy method that is nor part of the collection framework.

33) What is the difference between Set and Map? Set Map Set belongs to package-java.util. The map belongs package- java.util. It can extend the collection interface. It does not extend the collection interface. It does not allow duplicate values. It allows duplicate values. Set can sort only one null value. The map can sort multiple null values.

WeakHashMap is an implementation of the Java Map. It is used to store weak references to its keys. Sorting

using this Map allows a key-value pair is collected as garbage. Its key is not referenced outside

WeakHashMap.

39) What are the methods to make collection thread-safe?

The methods to make collection thread safe are:

 Collections.synchronizedList(list);

 Collections.synchronizedMap(map);

 Collections.synchronizedSet(set);

40) Explain UnsupportedOperationException

UnsupportedOperationException is an exception whch is thrown on methods that are not supported by

actual collection type.

For example, Developer is making a read-only list using “Collections.unmodifiableList(list)” and calling call(),

add() or remove() method. It should clearly throw UnsupportedOperationException.

41) Name the collection classes that gives random element access to its elements

Collection classes that give random element access to its elements are: 1) ArrayList, 2) HashMap, 3)

TreeMap, and 4) Hashtable.

42) Explain the difference between Queue and Deque. Queue Deque

It is called a single-ended Queue It is called a double-ended Queue Elements in the Queue are added or removed from one end Elements in the Queue are added from either end can be added and removed from the both end It is less versatile. It is more versatile. 43) Mention the implementing List and Set interface

Class implementing List interface: 1) ArrayList, 2) Vector, and 3) LinkedList.

Class implementing Set interface: 1) HashSet, and 2) TreeSet.

44) Explain the design pattern followed by Iterator

The iterator follows the detail of the iterator design pattern. It provides developer to navigate through the

objects collections using a common interface without knowing its implementation.

45) What is the peek() of the Queue interface?

Peek () is a method of queue interface. It retrieves all the elements but does not remove the queue head. In

case if the Queue is empty, then this method will return null.

46) What is CopyOnWriteArrayList?

CopyOnWriteArrayList is a variant of ArrayList in which operations like add and set are implemented by

creating a copy of the array. It is a thread-safe, and thereby it does not throw

ConcurrentModificationException. This ArrayLists permits all the elements, including null.

47) Differentiate between ArrayList and LinkedList

iterator iterator() It returns an iterator over the elements in this set. int size(): It returns the number of elements available in the set. 50) What are the methods of Java TreeSet class?

The methods of Java TreeSet class are:

Methods Descriptions boolean addAll(Collection c) Add all the elements in the specified collection to this set. boolean contains(Object o) Returns true if the set contains the mention element. boolean isEmpty() This Java method returns true if this set contains no elements. boolean remove(Object o) Remove the specified element from the set. void add(Object o) It adds the specified element to the set. void clear() This Java method removes all the elements from the set. 51) Explain Linked HashSet

Java LinkedHashSet class is a Linked list and Hash table implementation of the Set interface. It contains

unique elements same as a HashSet. Linked HashSet in Java also provides optional set operations that can

maintain the order of insertion.

52) What are the important methods used in a linked list?

The important methods used in the linked list are:

Method Description boolean add( Object o) It is used to append the specified element to the end of the vector. boolean contains(Object o) It a method that returns true if this list contains the specified element. void add (int index, Object element) Inserts the element at the specified element in the vector.

void addFirst(Object o) It is used to insert the given element at the beginning. void addLast(Object o) It is used to append the given element to the end. Int size() This method can be used to return the total number of elements in a list. boolean remove(Object o) It can remove the first occurrence of the specified element from this list. int indexOf(Object element) This Java method returns the index with the first occurrence of the mention element in this list, or -1. int lastIndexOf(Object element) It is a Java method that returns the index with the last occurrence of the specified element in this list, or -1. 53) List various classes available in sets

Various classes available in sets are: HashSet, TreeSetand, and LinkedHashSet.

54) List methods available in Java Queue interface

 boolean add(object)

 boolean offer(object)

 object remove()

 object poll()

 object element()

 object peek()

55) Differentiate between List and Set. List Set An ordered collection of elements An unordered collection of elements Preserves the insertion order Doesn’t preserves the insertion order Duplicate values are allowed Duplicate values are not allowed Any number of null values can be stored Only one null values can be stored