簡體   English   中英

如何在Lambda表達式中調用方法

[英]How to call method in lambda expression

我有3種方式來交換2個變量(基本上是3種不同的算法)。 由於您無法在Java中將方法作為參數傳遞,因此我認為這是使用lambda表達式的好時機。

chooseSwapMethod(int selection) {
    if(selection == 1) {
        functionThatUsesSwap(
            (int[] arr, int x, int y) -> {
                int holder = arr[x];
                arr[x] = arr[y];
                arr[y] = holder;
        });
    }
    else if(selection == 2)
    {
        functionThatUsesSwap(
            (int[] arr, int x, int y) -> {
                arr[x] -= arr[y];
                arr[y] = arr[x]-arr[y];
                arr[x] -= arr[y];
        });
    }
    else if(selection == 3) {
                functionThatUsesSwap(
            (int[] arr, int x, int y) -> {
                arr[x] = arr[x]^arr[y];
                arr[y] = arr[y]^arr[x];
                arr[x] = arr[x]^arr[y];
        });
    }
    else {
        throw new IllegalArgumentEarr[x]ception();
    }
}

但是在方法functionThatUsesSwap ,您實際上如何使用swap 我不是很清楚lambda表達式嗎? 例如

public void functionThatUsesSwap(Swaper s)
{
    int[] someArr = {1, 2};
    s.doSwap(someArr, 0, 1);//this is where I’m stuck
    System.out.println(“a: “+someArr[0]+” b: “+someArr[1]);//this should print out a: 2 b: 1
}

Java是按值傳遞的,這意味着:

int a = 5;
int b = 6;
swap(a,b);
System.out.println(a+" "+b);

沒有方法為函數swap改變的值ab ,其結果將總是5 6

您可以做的是:

  1. 將2個數字傳遞和數組到swap方法中,並在該數組內部交換數字。
  2. 讓一個班級持有2個數字並將其傳遞。

可能性2:

class Pair {
    int a, b;
}

@FunctionalInterface
interface Swapper {
    void swap(Pair p);
}

void main() {
    Pair p = new Pair();
    p.a = 5;
    p.b = 6;
    Swapper swapper = (v -> {
        v.a ^= v.b;
        v.b ^= v.a;
        v.a ^= v.b;
    });
    swapper.swap(p);
    System.out.println(p.a + " " + p.b);
}

結果: 6 5 請注意,您聲稱you can't pass a method as a parameter in Java說法並不完全正確,因為您可以傳遞接口。

編輯:

還有另一種方法(因為Interger類是不可變的,所以我之前沒有想到過)。 您可以為整數值創建一個可變的(=可更改的)對象vrapper,如下所示:

class IntVrapper {
    public int value;
}

然后,您的swap方法可以在這兩個對象之間交換數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM