Imposing constraints on method arguments, besides their number and their types, in Java

Viewed 78

I am trying to define a method (called "range") which returns an array. I pass two integers, say m and n, and it returns an array of length (n-m) as it is described in the following listing: Implicitly I suppose n is greater than m. But I would like to impose this condition explicitly. Is there any way to impose this kind of conditions on arguments of methods?

You may suggest I change the method so that I pass m and (n-m) instead of m and n into the method, but it still assumes that n-m is a positive integer. So we need to find a way to impose these types of constrains 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;
}
2 Answers
Related