Given:

public class Test<T> {

    private T t;

    public T get() {
        return t;
    }

    public void set(T t) {
        this.t = t;
    }

    public static void main(String args[]) {
        Test<String> type = new Test<>();
        Test type1 = new Test(); //line n1
        type.set("Java");
        type1.set(100); //line n2
        System.out.print(type.get() + " " + type1.get());
    }
}

What is the result?

A.

Java 100

B.

java.lang.string@<hashcode>java.lang.Integer@<hashcode>

C. A compilation error occurs. To rectify it, replace line n1 with:

Test<Integer> type1 = new Test<>();
D. A compilation error occurs. To rectify it, replace line n2 with:
type1.set(Integer(100));

题解

type 变量有使用到泛型,指定的型态为 String,所以 T 为 String。type1 变量则没有指定泛型,所以 T 可当作是 Object。

type1 对象的 set 方法,可以传入型态为 Object 的参数,因此所有型态的数据都可以传入,当然也包括整数对象(Integer)了。

「+」操作符若其中一个的操作数为字符串(对象)时,作为字符串连接的功用。对象会使用其「toString」方法来取得字符串。所以这题会输出「Java 100」。