Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 39
Question ID: UKOCP33145
Given code:
- package com.udayankhattry.ocp;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- public class Test {
- public static void main(String[] args) {
- var list = List.of("A", "E", "I", "O", "U"); //Line n1
- var set1 = Set.copyOf(list); //Line n2
- var map = Map.of(1, "U", 2, "O", 3, "I", 4, "E", 5, "A"); //Line n3
- var set2 = Set.copyOf(map.values()); //Line n4
- System.out.println(set1.equals(set2)); //Line n5
- }
- }
What is the result?
- A Compilation error at Line n2
- B Compilation error at Line n4
- C An exception is thrown by Line n2
- D An exception is thrown by Line n4
- E true
- F false
Reveal correct answer
Correct answer: E
Explanation
UKOCP33145:
Variable 'list' refers to unmodifiable List object containing 5 elements ["A", "E", "I", "O", "U"].
Variable 'map' refers to unmodifiable Map object containing 5 pairs [(1, "U"), (2, "O"), (3, "I"), (4, "E"), (5, "A")]
According to the Javadoc of copyOf method:
Returns an unmodifiable Set containing the elements of the given Collection. The given Collection must not be null, and it must not contain any null elements. If the given Collection contains duplicate elements, an arbitrary element of the duplicates is preserved. If the given Collection is subsequently modified, the returned Set will not reflect such modifications.
It throws NullPointerException if passed argument is null, or if it contains any nulls.
Variable 'set1' refers to unmodifiable Set Object containing 5 elements ["A", "E", "I", "O", "U"], order of elements is not significant.
At Line n4, map.values() returns Collection<String> object containing 5 elements ["U", "O", "I", "E", A"] and this object is passed as and argument to the copyOf method. Variable 'set2' refers to unmodifiable Set Object containing 5 elements ["U", "O", "I", "E", A"], order of elements is not significant.
According to the Javadoc of equals(Object) method of Set interface, it compares the specified object with this set for equality. Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set).
Both the sets contain same 5 elements "A", "E", "I", "O", U" and hence the output is true
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
