Is there an easy way/library to check and adjust parameters to stay inside the lists boundaries?
Here a long sample:
if (fromIndex < 0) {
fromIndex = 0;
}
if (fromIndex > list.size() - 1) {
fromIndex = list.size() - 1;
}
if (toIndex < 0) {
toIndex = 0;
}
if (toIndex > list.size() - 1) {
toIndex = list.size() - 1;
}
list.subList(fromIndex, toInd开发者_JAVA技巧ex);
I know i could move list.size() - 1
to a variable and do an extract-method on the index checks to remove redundant code. But it still seems a bit verbose for this simple task.
public int sanitize(int index) {
return Math.max(0, Math.min(index, this.length-1));
}
If you want to check all accesses to your list, it seems to me you want to wrap your list within a class implementing the List interface and intercept the accessor methods to check/modify the accessor indices.
e.g.
List sanitised = new SanitisedList(existingList);
This is an example of the Decorator pattern. Note how you just need one class defined (SanitisedList
) and you can apply that to any list you have. Use Zed's answer for a nice tidy bounds check.
You could use the ternary operator:
int listMax = list.size() - 1;
list.subList( fromIndex < 0 ? 0 : (fromIndex > listMax) ? listMax : fromIndex,
toIndex < 0 ? 0 : (toIndex > listMax) ? listMax : toIndex );
精彩评论