iSun
iSun

Reputation: 1754

How can I represent integer intervals in Java?

We all know about intervals in mathematics (e.g -4 < x < 3).

How can I represent these mathematic intervals in Java, e.g, the numbers between -4 and 3 (-4, -3, ..., 2, 3 etc)?

Upvotes: 12

Views: 37434

Answers (3)

tperrigo
tperrigo

Reputation: 31

Google Guava also has a Range class (https://guava.dev/releases/19.0/api/docs/com/google/common/collect/Range.html) that may work for you.

Upvotes: 3

Bozho
Bozho

Reputation: 597076

Check apache commons-lang IntRange. So, if you want to check if a number is in a given interval (range), you do:

IntRange range = new IntRange(-4, 3);
if (range.contains(x)) {
   ....
}

Upvotes: 18

djhaskin987
djhaskin987

Reputation: 10057

You simply have to separate -4 < x < 3 into -4 < x and x < 3, like this:

if (-4 < x && x < 3)
{
. . .
}

Upvotes: 4

Related Questions