As @Bohemian says, if you just want to test if two int values are equal:
public boolean equal(int a, int b) {
return a == b;
}
Don't call this method compare
, because the name compare
has strong connotations of a testing an ordering ... in Java. Whether it should be equal
or equals
is debatable.
(And @Bohemian's point about the above method being useless are apropos.)
This is what a proper compare method that implements int compare(int, int)
should look like1.
public int compare(int a, int b) {
if (a == b) {
return 0;
} else if (a < b) {
return -1;
} else {
return 1;
}
}
This is compatible with the semantics of Comparator::compare(T, T)
.
I also am not sure how to add the following constraints as well:
0 ≤ a, b ≤ 10000000
Add if
statements like this:
if (a < 0 || b > 10000000) {
throw SomeException("some message");
}
where SomeException
is the exception you are suppose to throw to indicate a constraint error.
Also, do I need to create a checker class that implements the comparator interface as well?
There is no specific reason that a checker class should implement Comparator
. Only do it if your checker needs to be used as a comparator.
Would this also work the same for strings with the following constraints:
1 ≤ |a|, |b| ≤ 2000
This approach would work for constraining the lengths of the string.
1 - It is quicker to show you the code than to explain what was wrong with your version. But compare them ... and you should be able to work that out.