lambda expression parameter passing

Lambda expressions using variables need to follow these rules:

 

1, can only refer to the outer local variables final mark, which means that the definition of local variables can not be modified within the extraterritorial application of lambda, otherwise compilation errors.
2, local variables declared as final may not, but must not be modified later in the code (i.e., the final having implicit semantics)
Parameter 3, permitted to declare a local variable with the same name or a local variable.
The following code compiler will complain:

public static void main(String args[]){
    List<String> dest = new ArrayList<>();
    List<String> src = new ArrayList<>(Arrays.asList("01", "02", "03"));
    src.forEach(item -> {
        add(dest,item);
    });
    dest = null;

}

Since the second rule violation (local variable can not be declared as final, but must not be modified later in the code (i.e., having a recessive semantic-final))

Slightly modified to remove the changes to dest, you can compile:

public static void main(String args[]){
    List<String> dest = new ArrayList<>();
    List<String> src = new ArrayList<>(Arrays.asList("01", "02", "03"));
    src.forEach(item -> {
        add(dest,item);
    });

}

By lambda expressions, local variables passed to the thread, and performs relevant operations:

    public static void main(String args[]){
        List<String> dest = new ArrayList<>();
        List<String> src = new ArrayList<>(Arrays.asList("01", "02", "03"));
        new Thread(()->add(dest,"a")).start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(dest.size());

    }

    private static void add(List<String>l,String item){
        l.add(item);
        System.out.println(item);
    }

 

Guess you like

Origin www.cnblogs.com/shuhe-nd/p/11532218.html