Site Search:

simulation Test 2--90 question set

Question: What is the output of the following code?

  1 import java.util.*;
  2 public class Products {
  3   private class Item<M> {}
  4   Map<Map<String, String>, Map<String, Set<Item<String>>>> products = new HashMap<>();
  5   public static void main(String...args) {
  6     Products pds = new Products();
  7     pds.test();
  8   }
  9   private void test() {
 10     HashMap<String, String> a = new HashMap<>();
 11     a.put("1","2");
 12     HashMap<String, Set<Item<String>>> b = new HashMap<>();
 13     Set<Item<String>> l = new HashSet<>();
 14     l.add(new Item<String>());
 15     l.add(new Item<Integer>());
 16     b.put("sports",l);
 17     products.put(a,b);
 18     System.out.println(products.get(a).get("sports").size());
 19   }
 20 }


A. compiler error at line 4
B. compiler error at line 11
C. compiler error at line 12
D. compiler error at line 13
E. compiler error at line 14
F. compiler error at line 15
G. compiler error at other lines
H. code compiles but throw exception at runtime
I. 2

Answer: F
Explain: line 13 limit the type of Set as Item<String>, however, at line 15, new Item<Integer> is added, which is an incompatible type. If line 15 is changed to l.add(new Item<String>()); the answer is I.
Study:  Create and use a generic class


================
================