Add checkInRange in ObjectUtil (#10668)

Motivation:
We check lots of numbers if it lies in a range. So it's better to add a method in `ObjectUtil` to check if a number lies inside a range.

Modification:
Added Range check method.

Result:
A faster and better way to check if a number lies inside a range.
This commit is contained in:
Aayush Atharva 2020-10-12 21:55:58 +05:30 committed by GitHub
parent 4c231a2e77
commit 9d457c3f0f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -79,6 +79,28 @@ public final class ObjectUtil {
return l; return l;
} }
/**
* Checks that the given argument is in range. If it is not, throws {@link IllegalArgumentException}.
* Otherwise, returns the argument.
*/
public static int checkInRange(int i, int start, int end, String name) {
if (i < start || i > end) {
throw new IllegalArgumentException(name + ": " + i + " (expected: " + start + "-" + end + ")");
}
return i;
}
/**
* Checks that the given argument is in range. If it is not, throws {@link IllegalArgumentException}.
* Otherwise, returns the argument.
*/
public static long checkInRange(long l, long start, long end, String name) {
if (l < start || l > end) {
throw new IllegalArgumentException(name + ": " + l + " (expected: " + start + "-" + end + ")");
}
return l;
}
/** /**
* Checks that the given argument is neither null nor empty. * Checks that the given argument is neither null nor empty.
* If it is, throws {@link NullPointerException} or {@link IllegalArgumentException}. * If it is, throws {@link NullPointerException} or {@link IllegalArgumentException}.