Here are 10 essential multiple-choice questions on Java Set and HashSet Classes, covering key concepts.
Question 1
Which of the following statements about Set in Java is correct?
Set allows duplicate elements
Set maintains insertion order
Set does not allow duplicate elements
Set allows duplicate elements but ignores null values
Question 3
What will be the output of the following code?
import java.util.*;
public class Test {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("Java");
System.out.println(set);
}
}
[Java, Python, Java]
[Java, Python]
[Python, Java, Java]
Compilation Error
Question 4
Which of the following is true about HashSet?
It maintains insertion order
It allows multiple null values
It does not maintain any specific order
It uses a balanced binary tree internally
Question 5
What is the time complexity of contains() operation in HashSet?
O(1)
O(n)
O(log n)
O(n log n)
Question 6
What will be the output of the following code?
import java.util.*;
public class Test {
public static void main(String[] args) {
Set<Integer> set = new TreeSet<>();
set.add(5);
set.add(3);
set.add(8);
set.add(1);
System.out.println(set);
}
}
[5, 3, 8, 1]
[1, 3, 5, 8]
[8, 5, 3, 1]
Compilation Error
Question 7
What is the key difference between LinkedHashSet and HashSet?
LinkedHashSet maintains insertion order, while HashSet does not
HashSet is synchronized, while LinkedHashSet is not
LinkedHashSet allows duplicate elements, while HashSet does not
LinkedHashSet is slower than HashSet for all operations
Question 8
What happens when you insert null in a TreeSet?
null is allowed and stored
null is ignored
It throws NullPointerException
TreeSet converts null to an empty string
Question 9
What will be the output of the following code?
import java.util.*;
public class Test {
public static void main(String[] args) {
Set<String> set = new LinkedHashSet<>();
set.add("C");
set.add("Java");
set.add("Python");
set.add("C");
System.out.println(set);
}
}
[C, Java, Python, C]
[Java, Python, C]
[C, Java, Python]
Compilation Error
Question 10
Which statement about HashSet, TreeSet, and LinkedHashSet is correct?
HashSet is the slowest in terms of performance
TreeSet provides the fastest insertion time
LinkedHashSet maintains insertion order
TreeSet allows duplicate elements
There are 10 questions to complete.