Popeye
Popeye

Reputation: 1558

Java loop strange behaviour

I have this split method inside which I have a loop. This loop is running 4 times but it should run 5 times. Any idea why is it behaving like this?

public static <T> List<List<T>> split(List<T> bigCollection, int maxBatchSize) {
        List<List<T>> result = new ArrayList<List<T>>();

        if (CollectionUtils.isEmpty(bigCollection)) {
            // return empty list
        } else if (bigCollection.size() < maxBatchSize) {
            result.add(bigCollection);
        } else {
            for (int i = 0; (i + maxBatchSize) <= bigCollection.size(); i = i + maxBatchSize) {
                result.add(bigCollection.subList(i, i + maxBatchSize));
            }

            if (bigCollection.size() % maxBatchSize > 0) {
                result.add(bigCollection.subList((int) (bigCollection.size() / maxBatchSize) * maxBatchSize,
                    bigCollection.size()));
            }
        }

        return result;
    }

    public static void main(String[] args) {
        List<String> coll = new ArrayList<String>();
        coll.add("1");
        coll.add("2");
        coll.add("3");
        coll.add("4");
        coll.add("5");
        coll.add("6");
        coll.add("7");
        coll.add("8");

        System.out.println(split(coll, 2));
    }

Output - [[1, 2], [3, 4], [5, 6], [7, 8]]

According to me this code should break when loop runs the fifth time and it tries to perform sublist function.

Upvotes: 0

Views: 83

Answers (2)

Tunaki
Tunaki

Reputation: 137064

The following for loop

for (int i = 0; (i + maxBatchSize) <= bigCollection.size(); i = i + maxBatchSize) {
    result.add(bigCollection.subList(i, i + maxBatchSize));
}

goes from 0 to bigCollection.size() - maxBatchSize by steps of maxBatchSize. In your example, bigCollection has size 8 and maxBatchSize is 2, so the loop goes from 0 to 6 by steps of 2. In total, that makes 4 steps : 0, 2, 4 and 6.

The following if

if (bigCollection.size() % maxBatchSize > 0)

is not executed because 8 % 2 = 0 (so the subList is not performed).

Upvotes: 1

Dimitri Mockelyn
Dimitri Mockelyn

Reputation: 1545

When you're at iteration 4, your loop condititoin is like this :

(i + maxBatchSize) <= bigCollection.size()
 6 + 2             <= 8

So you're going in. But the fifth iteration doesn't respect this condition anymore, because it's like this :

(i + maxBatchSize) <= bigCollection.size()
 8 + 2             <= 8

Don't forget that your condition isn't only on i but on i + maxBatchSize

Upvotes: 4

Related Questions