list.forEach(System.out::println) 为什么会这样 -- 已解决

list.forEach(System.out::println)

第一:来源
我不知道你是怎么知道的,我感觉 百分之九十 都是这样发现的:
有个集合我们需要打印内部的值,下列三种方法:

 		List<String> list = Arrays.asList("AA", "BB");
        //第一种
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        //第二种
        for (String s : list) {
            System.out.println(s);
        }
        //第三种 lambda 表达式
        list.forEach(s-> System.out.println(s));

在 idea 中:
list.forEach(System.out::println) 为什么会这样 -- 已解决_第1张图片
也就是可以简写 提示为:
list.forEach(System.out::println) 为什么会这样 -- 已解决_第2张图片
替换后就是:

list.forEach(System.out::println);

第二:导出 System.out::println 是什么 – 方法引用 java 8 新特性
方法引用是什么:一个对象的方法 地址引用 给一个接口中的方法 有条件
例如:

    interface TestInterface{
        void call();
    }

     class UseInterface{
        void call(){
            System.out.println("this is UseInterface");
        }
    }

    @Test
    public void test1() {
        TestInterface testInterface=new UseInterface()::call;
        testInterface.call();
    }

结果:

this is UseInterface

第三:查看源码:

list.forEach(System.out::println);

forEach() 的源码

    @Override
    public void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

所以:Consumer action = System.out::println;

即 进行拆分查看:
System.out :

public final static PrintStream out = null;

返回了 PrintStream 这里应该有值了

println:

public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
        //打印的方法
            print(s);
            newLine();
        }
    }

又返回 forEach() 源码:
大概会循环的 打印:

for (int i=0; modCount == expectedModCount && i < size; i++) {
            action.accept(elementData[i]);
        }

即已经解决;
list.forEach(System.out::println) 为什么会这样 -- 已解决_第3张图片
list.forEach(System.out::println) 为什么会这样 -- 已解决_第4张图片

你可能感兴趣的:(源码分析,方法引用,java)