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.

Java ジェネリクス・ラムダ式

Last updated at Posted at 2022-09-23

・ジェネリクス
ジェネリクスを使って宣言されたクラスは<〜>記法を利用できる。
Eは仮型引数という仮の型名でStringなどのインスタンスの型に置き換えられる。
(intなどの基本データは利用できない。ジェネリクスを用いたクラスの配列を作れない)

Pocket.java
public class Pocket<E>{
    private E data;
    public void put(E d) {this.data=d;}
    public E get(){return this.data;}
}

Eの型は制限をすることもできる

public class Pocket<E extends Character>

メソッドにも使える

public static <T> List<T> asList(T... a)

・ラムダ式
これを使うとメソッドにアルゴリズムを渡せる

import java.util.function.*;

public class Main{ 
    //[構文](型 引数名1、型 引数名2、・・・・)->{処理; return 戻り値;}
    public static void main(String[] args)throws Exception {
        Function<String, Integer>func=
            (String s)->{return s.length();};
        int n=func.apply("Java");
        System.out.println("文字列Javaは"+n+"文字です");      
    }

}
0
0
2

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?