Restrictions on method arguments, in addition to their number and their types, in Java

I am trying to define a method (called a "range") that returns an array. I pass two integers, for example m and n, and return an array of length (nm), as described in the following listing: I assume that n is greater than m. But I would like to impose this condition explicitly. Is there any way to impose such conditions on method arguments?

You can suggest me changing the method to pass m and (nm) instead of m and n into the method, but it still assumes that nm is a positive integer. Therefore, we need to find a way to impose these types of constraints on method arguments.

public static int[] range(int m, int n) {
    int[] r=new int[n-m];
    for(int i=0; i<n-m; i++)
        r[i]=m+i;

    return r;
}
+4
source share
2 answers

, ( , java).

, :

  • , - IllegalArgumentException
  • asserts ( , JVM )

: ; "" . "" - (, javadoc ).

+2

( ) -, , . . . , , , , , . Idris, Haskell. - , , , ( - ).

, , Java, - ( ), . , .

+4

Source: https://habr.com/ru/post/1683624/


All Articles