Ben Bitdiddle has written some generic Java code to run an iterator, storing the results into some output list: interfac

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
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

Post by answerhappygod »

Ben Bitdiddle Has Written Some Generic Java Code To Run An Iterator Storing The Results Into Some Output List Interfac 1
Ben Bitdiddle Has Written Some Generic Java Code To Run An Iterator Storing The Results Into Some Output List Interfac 1 (58.88 KiB) Viewed 35 times
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?
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply