編集の要約なし |
編集の要約なし |
||
| (同じ利用者による、間の18版が非表示) | |||
| 1行目: | 1行目: | ||
< [[Java基本文法]] | < [[Java基本文法]] | ||
* | * 機能オブジェクトとは、他のメソッドを再利用するための仕組み | ||
* メソッドを定義することなくロジックを利用したい場合は[[ラムダ式]]が利用できる | |||
* 機能オブジェクトを格納するには同じ戻り値と引数を定義した[[SAMインターフェース]]を使う | * 機能オブジェクトを格納するには同じ戻り値と引数を定義した[[SAMインターフェース]]を使う | ||
import java.util.function.*; | import java.util.function.*; | ||
public class Main { | public class Main { | ||
| 14行目: | 14行目: | ||
System.out.println("5 - 3" + ans); | System.out.println("5 - 3" + ans); | ||
} | } | ||
} | |||
==例== | |||
機能オブジェクトでは、ロジックを再利用しているのがポイント。[[ラムダ式#例|ラムダ式の例]]と比較。 | |||
# FuncList.java | |||
public class FuncList { | |||
public static boolean isOdd(int x) { return (x % 2 == 1); } | |||
public static String addMr(boolean male, String name) { | |||
if (male == true) { return "Mr." + name; } | |||
else { return "Ms." + name; } | |||
} | |||
} | |||
# Main.java | |||
interface Func1 { | |||
boolean call(int x); | |||
} | |||
interface Func2 { | |||
String call(boolean male, String name); | |||
} | |||
public class Main { | |||
public static void main(String[] args) { | |||
Func1 f1 = FuncList::isOdd; | |||
Func2 f2 = FuncList::addMr; | |||
System.out.println(f1.call(15)); | |||
System.out.println(f2.call(true, "Smith")); | |||
} | } | ||
2019年7月2日 (火) 20:28時点における最新版
< Java基本文法
- 機能オブジェクトとは、他のメソッドを再利用するための仕組み
- メソッドを定義することなくロジックを利用したい場合はラムダ式が利用できる
- 機能オブジェクトを格納するには同じ戻り値と引数を定義したSAMインターフェースを使う
import java.util.function.*;
public class Main {
public static int sub(int a, int b) {
return a - b;
}
public static void main(String[] args) {
IntBinaryOperator func = Main::sub;
int ans = func.applyAsInt(5, 3);
System.out.println("5 - 3" + ans);
}
}
例
機能オブジェクトでは、ロジックを再利用しているのがポイント。ラムダ式の例と比較。
# FuncList.java
public class FuncList {
public static boolean isOdd(int x) { return (x % 2 == 1); }
public static String addMr(boolean male, String name) {
if (male == true) { return "Mr." + name; }
else { return "Ms." + name; }
}
}
# Main.java
interface Func1 {
boolean call(int x);
}
interface Func2 {
String call(boolean male, String name);
}
public class Main {
public static void main(String[] args) {
Func1 f1 = FuncList::isOdd;
Func2 f2 = FuncList::addMr;
System.out.println(f1.call(15));
System.out.println(f2.call(true, "Smith"));
}