【问题标题】:What does the syntax mean in Java: new Stream<Integer>(){ ... }?Java 中的语法是什么意思:new Stream<Integer>(){ ... }?
【发布时间】:2010-02-02 12:45:12
【问题描述】:

我遇到了以下我不认识的 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() + ", ");  
}  

它是什么?

【问题讨论】:

    标签: java class syntax anonymous-inner-class


    【解决方案1】:

    这是提供Stream 类的内联(匿名)子类。

    从功能上来说,是一样的:

    public NewClass extends Stream {
        public Integer next() {  
           return 1; 
        }  
    }
    

    void someMethodInAnotherClass {
        Stream stream = new NewClass();
    }
    

    但由于该类定义不在方法体之外使用,您可以将其定义为匿名。

    【讨论】:

      【解决方案2】:

      ones = new Stream<Integer>() {
      public Integer next() {
      return 1; }
      };

      分配Stream&lt;Integer&gt; 的匿名实现的新实例(其中包含几乎无限数量的1s。您可以在Java In A Nutshell 中找到更多关于匿名类的信息

      【讨论】:

        【解决方案3】:

        这是定义一个实现 Stream 接口的匿名类。为了实现接口,我们接下来需要实现方法。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-13
          • 2012-12-18
          • 2013-11-02
          • 2011-01-24
          • 1970-01-01
          • 1970-01-01
          • 2012-05-05
          • 2023-03-29
          相关资源
          最近更新 更多