What's the best way to implement a generic range as a function argument in Java?

I have a function that needs a range as an argument. Domain is [0-100] and includes 0 and 100. A range argument can be, for example, the following:

[1-8, 18, 20-88, 90-92]

or

[1, 10-30]

The ranges do not overlap. I am interested in the mechanism - what is the best way to pass a range argument? Array? or use a variable argument?

+3


source to share


2 answers


Use a list of Range objects:

class Range
{
    int low;
    int high;

    Range(int low, int high)
    {
        this.low = low;
        this.high = high;
    }
}

List<Range> rangeArray = new ArrayList<Range>();

      



then assign the ranges like this:

rangeArray.add(new Range(1,8));
rangeArray.add(new Range(18,18));
rangeArray.add(new Range(20,88));
rangeArray.add(new Range(90,92));

      

+5


source


Have a static method r()

that creates a range in some view

func( r(1,8), r(18), r(20,88), r(90,92) )

      

Or use method chaining to create a list of ranges

func( Range.r(1,8).r(18).r(20,88).r(90,92) )

      



Or, as my comment on a joke

func(1,-8, 18, 20,-88, 90,-92)

      

Or, use 100*x+y

to represent(x,y)

func( 1_08, 18, 20_88, 90_92 );

      

+1


source







All Articles