I have a class in a Java project which contains a 2D array of values and provides useful methods for interacting with it. It uses Location objects (which just store two values) to access points in the mapping and return the value. It has a method isValid(), which checks whether the Location object is within the mapping of the grid.
public boolean isValid(Location loc) {
try {
// will throw an ArrayIndexOutOfBoundsException if not valid
// occs is the 2D array within the class
occs[loc.getX()][loc.getY()];
return true;
}
catch (ArrayIndexOutOfBoundsException e) {
return false;
}
}
Now, I know I could just use comparisons to check values and see if that loc fits within the grid, but this is faster as it does not need to run comparisons and the cases of non valid Locations being checked are far in the minority. However, here is my problem: since the value returned by the line accessing the array is not being assigned or sent into a method, I get an error about AssignmentOperators. I know it would be an easy fix to either assign it to a temp value or run it through some useless method, but both of those seem like derpy bandaid solutions to me, and I was wondering if there was a cleaner way to do that. (Besides, the former elicits a warning from Eclipse.)
Anyway, this is low priority, but it's bugging me that something so simple is not possible in such an easy implementation to be perfectly honest. Thanks!