Given:



public class Foo<K, V> {

    private K key;
    private V value;

    public Foo(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public static <T> Foo<T, T> twice(T value) {
        return new Foo<T, T>(value, value);
    }

    public K getKey() {
        return key;
    }

    public V getValue() {
        return value;
    }
}

Which option fails?

A.

Foo<String, Integer> mark = new Foo<String, Integer> ("Steve", 100);
B.
Foo<String, String> pair = Foo.<String>twice ("Hello World!");
C.
Foo<?, ?> percentage = new Foo<?, ?>(97, 32);
D.
Foo<String, String> grade = new Foo<>("John", "A");

題解

選項A,雖然是正確的泛型使用方式,但是在Java 7以後的版本,在實體化物件的時候,最好是省略new運算子泛型的型態,變成以下這樣:

Foo<String, Integer> mark = new Foo<> ("Steve", 100);

選項B,正確的泛型使用方式。

選項C,錯誤的泛型使用方式,「?」代表未知型態。應改成以下這樣:

Foo<?, ?> percentage = new Foo<>(97, 32);

或是指定明確的類別型態:

Foo<?, ?> percentage = new Foo<Integer, Integer>(97, 32);

選項D,正確的泛型使用方式。