0

This question is a follow up another question: Abstract class with default value

I am trying to define a abstract Range class which will serve as the base implementation of a number of range classes. The intended use is irrelevant for this question, but so far I have:

/**
 * Abstract generic utility class for handling ranges
 */
public abstract class Range<T extends Number> implements Collection<T>{

  // Variables to hold the range configuration
  protected T start;
  protected T stop;
  protected T step;

  /**
   * Constructs a range by defining it's limits and step size.
   *
   * @param start The beginning of the range.
   * @param stop The end of the range.
   * @param step The stepping
   */
  public Range(T start, T stop, T step) {
    this.start = start;
    this.stop = stop;
    this.step = step;
  }
}

(Irrelevant stuff omitted above)

Now I want to implement Collection, so I implement Size as following in my abstract class:

@Override
public int size() {
  return (this.stop - this.start) / this.step;
}

But Number seems to be to general for it to work. Do I need to implement this in the subclasses, or is there an abstract way?

Community
  • 1
  • 1
beruic
  • 5,517
  • 3
  • 35
  • 59
  • See also: http://stackoverflow.com/questions/25252441/if-any-object-of-the-java-abstract-class-number-is-equal-to-zero – assylias Aug 27 '14 at 11:58

1 Answers1

0

This should work:

@Override
public int size() {
  return (this.stop.doubleValue() - this.start.doubleValue()) / this.step.doubleValue();
}

See: http://docs.oracle.com/javase/8/docs/api/java/lang/Number.html#doubleValue--

Important note: if you're using Number implementations that require a better precision or a higher range than double, you have to override this method in your subclass. You should add that to your documentation.

J4v4
  • 780
  • 4
  • 9
pintxo
  • 2,085
  • 14
  • 27