Java OCA OCP Practice Question 2299

Question

Which declarations will compile without warnings?.

Select the four correct answers.

(a)  Map<Integer, Map<Integer, String>> map1
                    = new HashMap<Integer, HashMap<Integer, String>>();

(b)  Map<Integer, HashMap<Integer, String>> map2
                    = new HashMap<Integer, HashMap<Integer, String>>();

(c)  Map<Integer, Integer> map3 = new HashMap<Integer, Integer>();

(d)  Map<? super Integer, ? super Integer> map4
                   = new HashMap<? super Integer, ? super Integer>();

(e)  Map<? super Integer, ? super Integer> map5 = new HashMap<Number, Number>();

(f)  Map<? extends Number, ? extends Number> map6
                    = new HashMap<Number, Number>();

(g)  Map <?,?> map7 = new HashMap<?,?>();


(b), (c), (e), and (f)

Note

In (b), (c), (e), and (f), the parameterized type in the object creation expression is a subtype of the type of the reference.

This is not the case in (a): just because HashMap<Integer, String> is a subtype of Map<Integer, String>, it does not follow that HashMap<Integer, HashMap<Integer, String>> is a subtype of Map<Integer, Map<Integer, String>>-there is no subtype covariance relationship between concrete parameterized types.

In (d) and (g), wild cards cannot be used to instantiate the class.




PreviousNext

Related