Callable and Future How many Callable objects are there?
You are given a Callable object. Some say that it returns another Callable object. And that Callable returns another Callable object! And so on. You should find out how many Callable objects there are.
If the first iteration of call() method returns non-Callable object, your method should return 1.
Write a method that solves this problem.
Remember that if you cast a non-Callable object to a Callable, you will get an error doing that.
You may use instanceof operator to check whether the object is Callable or not.
import java.util.concurrent.*;
class FutureUtils {
public static int determineCallableDepth(Callable callable) throws Exception {
// write your code here
Object call = callable.call();
return call instanceof Callable ? 1 + determineCallableDepth((Callable) call) : 1;
}
}
import java.util.concurrent.*;
class FutureUtils {
public static int determineCallableDepth(Callable callable) {
Object result = callable;
int count = 0;
try {
while (result instanceof Callable) {
result = ((Callable) result).call();
count++;
}
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
}

浙公网安备 33010602011771号