Exception like java.lang.IllegalArgumentException: fromIndex(XXX) > toIndex(XX)

I have a jqgrid, with pagination. User can enter data by themselves to neviaget between pages.

I am getting error if user enter more than available pages on line 199 as shown in the above example. How to solve this issue?

if(noOfRows != null && !recipeList.isEmpty())
        if ((noOfRows * pageNo) < recipeList.size()) {
            recipeList = recipeList.subList((noOfRows * (pageNo - 1)),
                    (noOfRows * pageNo));
        } else {
            recipeList = recipeList.subList((noOfRows * (pageNo - 1)), 
                    recipeList.size());  //line 199:  giving error
        }
    for (Recipe recp : recipeList) {
             ..............
             ..............

I tried to change the else part of code where on line 199 :

  int totalCustomPagesNums=noOfRows * (pageNo - 1); 
        int firstIndex=totalCustomPagesNums < recipeIdList.size()?totalCustomPagesNums:1;
        recipeList = recipeList.subList(firstIndex,
         recipeList.size());
Jon Skeet
people
quotationmark

I would simplify it to:

  • Work out the lower bound, which must be at least 0 and at most recipeList.size()
  • Work out the exclusive upper bound, which must be at least 0 and at most recipeList.size()
  • Take the sublist

So:

int start = Math.min(Math.max(noOfRows * (pageNo - 1), 0), recipeList.size());
int end = Math.min(Math.max(noOfRows * pageNo, start), recipeList.size());
recipeList = recipeList.subList(start, end);

Now you know for sure that 0 <= start <= end <= recipeList.size(), so it'll be fine, even if the user specifies bizarre row counts or page numbers.

people

See more on this question at Stackoverflow