class AAICreateTasks {

    protected int calculateUnusedIndex(TreeSet<Integer> moduleIndices, int nullIndexFound) {
        // pad array with nulls
        Integer[] temp = new Integer[moduleIndices.size() + nullIndexFound];
        Integer[] array = moduleIndices.toArray(temp);
        int result = 0;
        // when a null is found skip that potential value
        // effectively creates something like, [0,1,3,null,null] -> [0,1,null(2),3,null(4)]
        for (int i = 0; i < array.length; i++, result++) {
            if (Integer.valueOf(result) != array[i]) {
                if (nullIndexFound > 0) {
                    nullIndexFound--;
                    i--;
                } else {
                    break;
                }
            }
        }

        return result;
    }

}