Hmahwish
Hmahwish

Reputation: 2232

IndexOutOfBoundsException in Java on getting sub string

I have to divide a list of string in chunks ,hence I have written this method ,

public static List<List<String>> chunkIds(List<String> ids,
        int max) {
    List<List<String>> chunks = new ArrayList<>();
    for (int i = 0; i < ids.size(); i = i + max) {
        List<String> chunk = ids.subList(i, i + max);
        chunks.add(chunk);
    }
    return chunks;
}

when I call the method I get IndexOutOfBoundsException on getting the subList .where max is a chunk size .Could someone please help me understand the index logic wrong here.

Upvotes: 1

Views: 101

Answers (2)

wylasr
wylasr

Reputation: 117

List<String> chunk = ids.subList(i, i + max);

what is max? i + max should not be greater than ids.size()

Upvotes: 1

Andy Turner
Andy Turner

Reputation: 140544

If you use i + max as the second parameter to subList, if ids.size() isn't exactly divisible by max, that index will be greater than ids.size().

Use

Math.min(i + max, ids.size())

instead of i + max.

Or, avoiding calculating the min each time:

int i;
for (i = 0; i + max < ids.size(); i += max) {
  chunks.add(ids.subList(i, i + max));
}
if (i < ids.size()) {
  chunks.add(ids.subList(i, ids.size());
}

Upvotes: 2

Related Questions