Java 中的语法含义是什么:new Stream(){ ... }?
我遇到过以下我不认识的 Java 语法。
这部分很好:
public abstract class Stream<T> implements Iterator<T> {
public boolean hasNext() {
return true; }
public void remove() {
throw new RuntimeException("Unsupported Operation"); }
}
但是我不明白:
Stream<Integer> ones = new Stream<Integer>() {
public Integer next() {
return 1; }
};
while(true){
System.out.print(ones.next() + ", ");
}
这是什么?
I have encountered the following Java syntax that I don't recognize.
This part is fine:
public abstract class Stream<T> implements Iterator<T> {
public boolean hasNext() {
return true; }
public void remove() {
throw new RuntimeException("Unsupported Operation"); }
}
But this I don't get:
Stream<Integer> ones = new Stream<Integer>() {
public Integer next() {
return 1; }
};
while(true){
System.out.print(ones.next() + ", ");
}
What it is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这提供了 Stream 类的内联(匿名)子类。
相同
从功能上讲,它与: and
,但由于此类定义不在方法体之外使用,因此您可以将其定义为匿名。
This is providing an inline (anonymous) subclass of the
Stream
class.Functionally, it is the same as:
and
but as this class definition isn't used outside the method body, you can define it as anonymous.
ones = new Stream() {
公共整数 next() {
返回1; }
分配
Stream
匿名实现的新实例(包含几乎无限数量的1
。您可以在匿名上找到更多信息Java 简述中的类ones = new Stream<Integer>() {
public Integer next() {
return 1; }
};
Assigns a new instance of an anonymous implementation of
Stream<Integer>
(that contains a virtually unlimited number of1
s. You may find more on anonymous classes in Java In A Nutshell这是定义一个实现 Stream 接口的匿名类。为了实现该接口,我们接下来需要实现该方法。
This is defining a Anonymous class which implements the Stream interface. To implement the interface we need to implement the method next.