简体   繁体   English

如何重新设计一个Progression类在java中是抽象的和通用的?

[英]How to redesign a Progression class to be abstract and generic in java?

I have the following Progression class: 我有以下Progression类:

/** 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();
  }
}

How do I redesign the above java Progression class to be abstract and generic, producing a sequence of values of generic Type T, and supporting a single constructor that accepts an initial value? 如何将上面的Java Progression类重新设计为抽象和泛型,生成一系列通用类型T的值,并支持一个接受初始值的构造函数?

I understand how to make the above class abstract but I don't see or understand how to translate the class to generics. 我理解如何使上面的类抽象,但我没有看到或理解如何将类转换为泛型。 In particular I don't know how to redesign the advance() method so that it uses java generics to produce a sequence of values of generic Type T. 特别是我不知道如何重新设计advance()方法,以便它使用java泛型来生成通用类型T的值序列。

You can only code what you know to hold for all generic instantiations. 您只能为所有通用实例编写您知道的内容。 Everything else remains abstract. 其他一切都是抽象的。 This can be seen by looking at the (added) method getInitial: it would return 0 for a Long, but (perhaps) "A" for a String. 这可以通过查看(添加的)方法getInitial来看出:它将为Long返回0,但是(或许)为String返回“A”。 Also, nextValue is illuminating: it calls advance (no matter how) but advance is left to the implementation of the instantiation. 此外,nextValue是有启发性的:它调用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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM