Java中方法引用與Lambda區別 - foojay

banq發表於2021-07-01

lambda和方法引用之間有一個關鍵的區別:Lambda 是惰性的,它們只會在呼叫方法時呼叫類建構函式。另一方面,對於方法引用,建構函式只會在分配了方法引用的地方被立即呼叫,而不是在方法呼叫時呼叫。

public class MethodReferenceVSLambdaChallenge {

    public static void main(String... doYourBest) {
        Runnable universeImpactRunnable = () -> new ChuckNorris().roundHouseKick();
        Runnable galaxyImpactRunnable = new ChuckNorris()::roundHouseKick;

        System.out.print("The galaxy is finished = ");

        universeImpactRunnable.run();
        universeImpactRunnable.run();

        galaxyImpactRunnable.run();
        galaxyImpactRunnable.run();
    }

    static class ChuckNorris {
        private static int numberOfKicks;
        private int galaxyDamage;

        ChuckNorris() {
            this.galaxyDamage = numberOfKicks++;
        }

        void roundHouseKick() {
            System.out.print(this.galaxyDamage);
        }
    }

}


結果:
A) The galaxy is finished = 1234
B) The galaxy is finished = 0123
C) The galaxy is finished = 0100
D) The galaxy is finished = 1200

在下面這行並沒有呼叫建構函式:

Runnable universeImpactRunnable = () -> new ChuckNorris().roundHouseKick();

而是在下行呼叫了建構函式:

Runnable galaxyImpactRunnable = new ChuckNorris()::roundHouseKick;

  
再看看:

universeImpactRunnable.run();
universeImpactRunnable.run();


當我們呼叫這些方法時:值將為 0,因為請記住,建構函式只會被呼叫一個,並且在方法引用宣告的那一刻它已經被呼叫了。

相關文章