Java-generics-no-primitive
提供:Dev Guides
Javaジェネリック-プリミティブ型なし
ジェネリックを使用すると、プリミティブ型を型パラメーターとして渡すことはできません。 以下の例では、ボックスクラスにintプリミティブ型を渡すと、コンパイラーは文句を言います。 同じことを緩和するには、intプリミティブ型の代わりにIntegerオブジェクトを渡す必要があります。
例
package com.finddevguides;
public class GenericsTester {
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
//compiler errror
//ReferenceType
//- Syntax error, insert "Dimensions" to complete
ReferenceType
//Box<int> stringBox = new Box<int>();
integerBox.add(new Integer(10));
printBox(integerBox);
}
private static void printBox(Box box) {
System.out.println("Value: " + box.get());
}
}
class Box<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
}
これは、次の結果を生成します-
出力
Value: 10