[英]Use different methods based on an integer value
這是我無法理解的東西,現在我有這樣的東西:
boolean method1(int a){
//something
returns true;
}
boolean method2(int a){
//something
returns true;
}
for (int i; i<100; i++){
switch (someInt){
case 1: boolean x = method1(i);
case 2: boolean x = method2(i);
}
}
我想要的是把開關帶出循環,因為someInt將保持相同的每個i,因此需要只決定一次,但我需要x檢查每一個,所以我需要像:
switch (someInt){
case 1: method1(); //will be used in loop below
case 2: method2(); //will be used in loop below
}
for (int i; i<100; i++){
boolean x = method the switch above picked
}
您可以使用Java 8方法引用。
這是一個例子:
public class WithMethodRefs {
interface MyReference {
boolean method(int a);
}
boolean method1(int a) {
return true;
}
boolean method2(int a) {
return false;
}
public void doIt(int someInt) {
MyReference p = null;
switch (someInt) {
case 1:
p = this::method1;
break;
case 2:
p = this::method2;
break;
}
for (int i = 0; i < 100; i++) {
p.method(i);
}
}
}
您可以用多態替換條件:
一些例子:
您的代碼示例:
interface CallIt {
boolean callMe(int a);
}
class Method1 implements CallIt {
public boolean callMe(int a) {
return true;
}
}
class Method2 implements CallIt {
public boolean callMe(int a) {
return true;
}
}
void doIt(int someInt) {
CallIt callIt = null;
switch (someInt) {
case 1:
callIt = new Method1();
break;
case 2:
callIt = new Method2();
break;
}
for (int i = 0; i < 100; i++) {
boolean x = callIt.callMe(i);
}
}
我的兩分錢。 如果我們開始實現功能,那就讓它一直持續到最后!
IntFunction<IntFunction<Boolean>> basic = x -> i -> {
switch (x) {
case 1: return method1(i);
case 2: return method2(i);
default:
throw new RuntimeException("No method for " + someInt);
}
};
IntFunction<Boolean> f = basic.apply(someInt);
IntStream.range(0, 100).forEach(i -> {
boolean result = f.apply(i);
//do something with the result
});
此外,我在您的交換機中看不到任何break語句。 也許是因為這只是一個例子,但要檢查它們是否在這里。 否則,您將獲得所有情況的method2()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.