Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining Java variables that only accept a specific range of values

Is there a built-in way to define fields/variables accepting values in a specific range? I mean a way of resolving it in compile-time.

For example, defining a double variable that only takes values between 1-10.

like image 360
Zahra Avatar asked Mar 21 '13 18:03

Zahra


2 Answers

The closest you can get is

1) create an Enum for your range of values, that's what Enums are for.

public Enum MyVals {
   ONE(1)
   TWO(2)
   ...

   private int val;
   MyVals(int val) {
      this.val = val;
   }
}

see this. Of course this will only work if the values are discrete (i.e. not floats)

2) make the field private and write a smart setter that blows up on an unacceptable value.

public void setVal(int val) {
   if (val < 0 || val > 10) throw....;
   this.val = val;
}
like image 104
hvgotcodes Avatar answered Sep 20 '22 03:09

hvgotcodes


Nope, since in compilation time there is no way to know if your software logic will produce values out of range. And in runtime there is no implementation for it supported by the native sdk. You can however wrap the type classes (e.g. Create class MyInteger with an Integer instance as a member wrapped by range verification methods in the MyInteger class)

like image 25
giorashc Avatar answered Sep 23 '22 03:09

giorashc