MeanwhileInHell
MeanwhileInHell

Reputation: 7053

Checking if ArrayList element exists or not

I'll try to explain this as best I can. I have an ArrayList of String's. I am trying to implement server-side paging for a webapp. I am restricted to the number of items per page (6 in this case) which are read from this ArrayList. The ArrayList is, lets say, the entire catalog, and each page will take a section of it to populate the page. I can get this working just fine when there are enough elements to fill the particular page, its when we hit the end of the ArrayList where there will be less than 6 items remaining for that pages segment. How can I check if the ArrayList is on its last element, or if the next one doesn't exist? I have the following code (in pseudo-ish code):

int enterArrayListAtElement = (numberOfItemsPerPage * (requestedPageNumber - 1));
for (int i = 0; i < numberOfItemsPerPage; i++) {
    if (!completeCatalog.get(enterArrayListAtElement + i).isEmpty() {
        completeCatalog.get(enterArrayListAtElement + i);
    }
}

The if in the code is the problem. Any suggestions will be greatly appreciated.

Thanks.

Upvotes: 0

Views: 4224

Answers (4)

Farrell
Farrell

Reputation: 508

An ArrayList has the method of size(), which returns the number of elements within the List.

Therefore, you can use this within the if statement to check you've not went too far.
For example,

if(enterArrayListAtElement + i < completeCatalog.size()) {
   ...
}

Upvotes: 0

S&#246;ren
S&#246;ren

Reputation: 2741

You just need to add a second expression to look whether the end of the list was reached already:

int enterArrayListAtElement = (numberOfItemsPerPage * (requestedPageNumber - 1));
for (int i = 0; i < numberOfItemsPerPage; i++) {
    if (enterArrayListAtElement + i < completeCatalog.size() && !completeCatalog.get(enterArrayListAtElement + i).isEmpty() {
        completeCatalog.get(enterArrayListAtElement + i);
    }
}

Upvotes: 0

Tom Quarendon
Tom Quarendon

Reputation: 5716

Can't you just get

completeCatalog.size()

and compare it to i? i.e to answer the question "is there an ith element" you say

 if (i<completeCatalog.size())

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504082

It sounds like you want:

if (enterArrayListAtElement + i < completeCatalog.size())

That will stop you from trying to fetch values beyond the end of the list.

If that's the case, you may want to change the bounds of the for loop to something like:

int actualCount = Math.min(numberOfItemsPerPage,
                           completeCatalog.size() - enterArrayListAtElement);
for (int i = 0; i < actualCount; i++) {
    // Stuff
}

(You may find this somewhat easier to format if you use shorter names, e.g. firstIndex instead of enterArrayListAtElement and pageSize instead of numberOfItemsPerPage.)

Upvotes: 4

Related Questions