:: 在 Java 语法中的含义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27015495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Meaning of :: in Java syntax
提问by sixfeet
What is the meaning of ::in the following code?
下面代码中::是什么意思?
Set<String> set = people.stream()
.map(Person::getName)
.collect(Collectors.toCollection(TreeSet::new));
采纳答案by Eran
This is method reference. Added in Java 8.
这是方法参考。在 Java 8 中添加。
TreeSet::new
refers to the default constructor of TreeSet
.
TreeSet::new
指的是 的默认构造函数TreeSet
。
In general A::B
refers to method B
in class A
.
一般A::B
指B
类中的方法A
。
回答by jbutler483
::
is called Method Reference. It is basically a reference to a single method. i.e. it refers to an existing method by name.
::
称为方法参考。它基本上是对单个方法的引用。即它按名称引用现有方法。
Method reference using ::
is a convenienceoperator.
Method reference using ::
是一个便利运算符。
Method reference is one of the features belonging to Java lambda expressions. Method reference can be expressed using the usual lambda expression syntax format using –>
In order to make it more simple ::
operator can be used.
方法引用是属于Java lambda 表达式的特性之一。方法引用可以使用通常的 lambda 表达式语法格式 using 来表示–>
,以使其更简单,::
可以使用运算符。
Example:
例子:
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) {
}
}
}
So, In your example:
所以,在你的例子中:
Set<String> set = people.stream()
.map(Person::getName)
.collect(Collectors.toCollection(TreeSet::new));
Is calling/creating a 'new' treeset.
正在调用/创建“新”树集。
A similar example of a Contstructor Reference is:
构造函数引用的一个类似示例是:
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());
}
}
回答by Misha
Person::getName in this context is shorthand for (Person p) -> p.getName()
Person::getName 在这种情况下是简写 (Person p) -> p.getName()
See more examples and a detailed explanations in JLS section 15.13
在JLS 第 15.13 节中查看更多示例和详细说明