generics class sample
paramをgenericsで定義
instance化する際に、concreteなclassを指定する
Putlog.java
public class Putlog <T>{
private T param;
public Putlog(T p1) {
this.param = p1;
}
public void setPlog(T p1) {
this.param = p1;
}
public void outlog() {
System.out.println(param);
}
}
sample.java
public static void main(String[] args) {
Putlog p = new Putlog("a1");
p.outlog();
p = new Putlog(1);
p.outlog();
}
実行結果
a1
1
generics methodは、return valueの前に型パラメータを置く
static <T> Optional<T> get(T[] array, int index) {
if(array == null) {
return Optional.empty();
} else {
try {
return Optional.ofNullable(array[index]);
} catch (ArrayIndexOutOfBoundsException ex) {
return Optional.empty();
}
}
}