【问题标题】:Meaning of :: in Java syntax [duplicate]Java语法中::的含义[重复]
【发布时间】:2014-11-19 11:16:21
【问题描述】:

下面代码中::是什么意思?

Set<String> set = people.stream()
                        .map(Person::getName)
                        .collect(Collectors.toCollection(TreeSet::new));

【问题讨论】:

    标签: java syntax java-8


    【解决方案1】:

    这是方法参考。在 Java 8 中添加。

    TreeSet::new指的是TreeSet的默认构造函数。

    一般A::B指的是A类中的方法B

    【讨论】:

    • +1,他们接下来会怎么想?可能是字符串切换...接口与方法...
    • @Bathsheba,我正在祈祷运算符重载。
    • @ChiefTwoPencils 特别是如果他们还将, 定义为运算符。
    • @Bathsheba 默认和静态方法自 1.8 起在接口中可用
    【解决方案2】:

    :: 称为方法参考。它基本上是对单一方法的引用。即它通过名称引用现有方法。

    Method reference using :: 是一个方便运算符。

    方法引用是属于Java lambda expressions 的功能之一。方法引用可以使用通常的 lambda 表达式语法格式使用–&gt; 来表达,为了更简单可以使用:: 运算符。

    例子:

    public class MethodReferenceExample {
        void close() {
            System.out.println("Close.");
        }
    
        public static void main(String[] args) throws Exception {
            MethodReferenceExample referenceObj = new MethodReferenceExample();
            try (AutoCloseable ac = referenceObj::close) {
            }
        }
    }
    

    所以,在你的例子中:

    Set<String> set = people.stream()
                            .map(Person::getName)
                            .collect(Collectors.toCollection(TreeSet::new));
    

    正在调用/创建一个“新”树集。

    构造函数引用的类似示例是:

    class Zoo {
        private List animalList;
        public Zoo(List animalList) {
            this.animalList = animalList;
            System.out.println("Zoo created.");
        }
    }
    
    interface ZooFactory {
        Zoo getZoo(List animals);
    }
    
    public class ConstructorReferenceExample {
    
        public static void main(String[] args) {
            //following commented line is lambda expression equivalent
            //ZooFactory zooFactory = (List animalList)-> {return new Zoo(animalList);};    
            ZooFactory zooFactory = Zoo::new;
            System.out.println("Ok");       
            Zoo zoo = zooFactory.getZoo(new ArrayList());
        }
    }
    

    【讨论】:

      【解决方案3】:

      Person::getName 在此上下文中是 (Person p) -&gt; p.getName() 的简写

      JLS section 15.13查看更多示例和详细解释

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多