你知道java里面的this:: 双冒号是干什么的吗?

33 篇文章 1 订阅

今天看到一行java代码:

 nodes.forEach(this::buildTree);

this::buildTree是个什么鬼东西,还整个双冒号,java现在这么奔放了么???
foreach肯定不用说了,this肯定指的是当前nodes,机智的我按住了Ctrl点了下双冒号后面的东西,发现这是个迭代方法,结合需求初步猜测双冒号的功能是把前面集合的每一个对象一次去执行冒号后面的方法。
后面经过百度,发现::是java8 中新引入的运算符,是把方法当做参数传到stream内部,使stream的每个元素都传入到该方法里面执行一下,跟俺猜的基本上差不多。
 在JDK8中,接口Iterable 8中默认实现了forEach方法,调用了 JDK8中增加的接口Consumer内的accept方法,执行传入的方法参数。

JDK源码如下,从第二十行我们大致可以看到其实现原理:

/**
     * Performs the given action for each element of the {@code Iterable}
     * until all elements have been processed or the action throws an
     * exception.  Unless otherwise specified by the implementing class,
     * actions are performed in the order of iteration (if an iteration order
     * is specified).  Exceptions thrown by the action are relayed to the
     * caller.
     *
     * @implSpec
     * <p>The default implementation behaves as if:
     * <pre>{@code
     *     for (T t : this)
     *         action.accept(t);
     * }</pre>
     *
     * @param action The action to be performed for each element
     * @throws NullPointerException if the specified action is null
     * @since 1.8
     */
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值