naltatis
naltatis

Reputation: 3123

simplified boundary checking for Java List

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, toIndex);

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.

Upvotes: 0

Views: 687

Answers (3)

B Johnson
B Johnson

Reputation: 2556

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 );

Upvotes: 0

Zed
Zed

Reputation: 57648

public int sanitize(int index) {
  return Math.max(0, Math.min(index, this.length-1));
}

Upvotes: 5

Brian Agnew
Brian Agnew

Reputation: 272217

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.

Upvotes: 3

Related Questions