0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Generics サンプル

Last updated at Posted at 2022-12-15

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();
            }
        }
    }
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?