开发者

Is it possible to create a float type with a min and max range?

I know this 开发者_运维问答can be done in Ada but I'm new to Java and don't know if I can do this. I would like to make a radian of float subtype from 0 to 2pi. Values outside the range would be considered out of range and through a constraint error. Any help is appreciated!


commons.lang.math.Range just specifies the range constraint. It does not represent a value in that range (which I think is what you want).

You could create a new class to hold the value and enforce the constraint. Your own program would pass instances of this class around and would thus get the type safety (of having the constraint enforced). When calling other API, you have to revert back to sending and accepting regular double values. You can check the constraint again before accepting return values.

public class Radian extends Number {

     private final double value;

     public Radian(double value){
          if (value < 0 || value >= 2 * PI)
               throw new IllegalArgumentException(value + " is out of range");
          this.value = value;
     }

     public double doubleValue(){
         return value;
     }

     // ... and other methods in the Number interface
     //   don't forget equals and hashCode and toString
}


There's no Range object built into Java, but you could always use something from Apache Commons http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/Range.html


Java has no way to declare an Ada-like subtype of a primitive type, and specifically no way to declare types that are subranges of primitive types.

The best you can do in Java is create a custom wrapper class for a primitive type and have the wrapper enforce the range constraints using (purely) runtime checks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜