Ben Bitdiddle has written some generic Java code to run an iterator, storing the results into some output list: interface Iterator<T> { bool hasNext(); T next(); } interface List<T> { void add (T); } static public <T> void copyTo (Iterator<T> it, List<T> out) { while (it.hasNext()) out.add(it.next()); } Alyssa P. Hacker has a Iterator<Integer> and would like to copy it into an array of type List<Number> (Integer is a subtype of Number). However, she discovers that she cannot do so!
(a) There are a few more general type signatures for copyTo which will work with Alyssa's use case, without changing the body of copyTo at all. Give TWO such signatures. (b) Sally Scallion suggests that if Java only had declaration-site variance annotations, in which we annotate type parameters of interfaces as covariant or contravariant, we would then be able to derive that Iterator<Integer> was a subtype of Iterator<Number>, and so forth. For the Iterator and List we have defined above, what are their variances?
Ben Bitdiddle has written some generic Java code to run an iterator, storing the results into some output list: interfac
-
answerhappygod
- Site Admin
- Posts: 899604
- Joined: Mon Aug 02, 2021 8:13 am
Ben Bitdiddle has written some generic Java code to run an iterator, storing the results into some output list: interfac
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!