Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 103
Question ID: UKOCP81279
Given code:
- package com.udayankhattry.ocp;
- import java.util.*;
- import java.util.function.*;
- public class Test {
- public static void main(String[] args) {
- Set<Integer> set = new HashSet<>();
- add(set, s -> s.add(10)); //Line n1
- add(set, s -> s.add(20)); //Line n2
- System.out.println(set.size());
- }
- private static void add(Set<Integer> set, Consumer<Set<Integer>> consumer) { //Line n3
- consumer.accept(set);
- }
- private static void add(Set<Integer> set, Predicate<Set<Integer>> predicate) { //Line n4
- predicate.test(set);
- }
- }
What is the result?
- A 0
- B 1
- C 2
- D Compilation error
Reveal correct answer
Correct answer: D
Explanation
UKOCP81279:
s -> s.add(10) an ambiguous call and it matches to 2nd argument of both the overloaded methods.
Consumer<Set<Integer>> consumer = s -> s.add(10);
and
Predicate<Set<Integer>> predicate = s -> s.add(10);
So, both Line n1 and Line n2 cause compilation error.
There are 3 ways to resolve the error:
1. Use the reference variable of particular type:
Consumer<Set<Integer>> consumer = s -> s.add(10);
add(set, consumer); //Line n1 => Matches to method at Line n3
Predicate<Set<Integer>> predicate = s -> s.add(20);
add(set, predicate); //Line n2 => Matches to method at Line n4
2. Typecast to exact type:
add(set, (Consumer<Set<Integer>>)s -> s.add(10)); //Line n1 => Matches to method at Line n3
add(set, (Predicate<Set<Integer>>)s -> s.add(20)); //Line n2 => Matches to method at Line n4
3. Use the lambda expression with body:
add(set, s -> {s.add(10); return;}); //Line n1 => Matches to method at Line n3
add(set, s -> {return s.add(20);}); //Line n2 => Matches to method at Line n4
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
