java - 如何在 java 中将 Progression 类重新设计为抽象和通用的?

标签 java

我有以下进阶类(class):

/** Generates a simple progression. By default: 0,1,2,3...*/
public class Progression {

// instance variable
protected long current;

/** Constructs a progression starting at zero. */
public Progression() { this(0); }

/** Constructs a progression with a given start value. */
public Progression(long start) { current = start; }

/** Returns the next value of the progression.*/
public long nextValue() {
   long answer = current;
   advance();
   return answer;
}

/** Advances the current value to the next value of the progression */
protected void advance() {
   current++;
}

/** Prints the next value of the progression, separated by spaces .*/
public void printProgression(int n) {
   System.out.print(nextValue());
   for(int j = 1; j < n;j++)
      System.out.print(" " + nextValue());
   System.out.println();
  }
}

如何将上述 java Progression 类重新设计为抽象和泛型,生成泛型 T 类型的值序列,并支持接受初始值的单个构造函数?

我了解如何将上述类抽象化,但我没有看到或理解如何将类转换为泛型。特别是我不知道如何重新设计 advance() 方法,以便它使用 java 泛型来生成泛型类型 T 的值序列。

最佳答案

您只能编写您知道的所有通用实例的代码。其他一切都保持抽象。这可以通过查看(添加的)方法 getInitial 看出:它将为 Long 返回 0,但(可能)为 String 返回“A”。此外,nextValue 很有启发性:它调用 advance(无论如何),但 advance 留给实例化的实现。

public abstract class Progression<T> {
    protected T current;

    public Progression() { this( getInitial()); }
    protected abstract T getInitial();
    public Progression(T start) { current = start; }

    public T nextValue() {
         T answer = current;
         advance();
         return answer;
    }

    protected abstract void advance();

    public void printProgression(int n) {
        System.out.print(nextValue());
        for(int j = 1; j < n;j++)
            System.out.print(" " + nextValue());
        System.out.println();
    }
}

关于java - 如何在 java 中将 Progression 类重新设计为抽象和通用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28739915/

相关文章:

java - 具有许多必需参数的构造函数

java - 如何创建具有可变对象作为引用的不可变类

Java/Javascript/JSON - 将 JSON 字符串从 Java 传递到 Javascript

java - 警告 : No mapping found for HTTP request with URI [/mvc/add] in DispatcherServlet with name 'dispatcherservlet'

java - 单词前面没有正则表达式

java - 异步使用 Struts 2

java - 在java程序中,如何知道存储过程运行正确或引发一些错误?

java - 使用 JFileChooser 和文件处理

java - 如何在我的jsp中使用update语句

java - 如何使用 Java 将 xml 样式表包含到 XML 文件中