TheAlgorithms/Java · error · IllegalArgumentException

Array contains negative integers.

Error message

Array contains negative integers.

What it means

Thrown by PigeonholeSort.checkForNegativeInput(int[]) when any element is negative. Pigeonhole sort allocates one hole per value in [0, max], so negative indices would fall outside the hole array. The private check is invoked during sort and rejects negatives before hole creation.

Source

Thrown at src/main/java/com/thealgorithms/sorts/PigeonholeSort.java:44

        final int maxElement = Arrays.stream(array).max().orElseThrow();
        final List<List<Integer>> pigeonHoles = createPigeonHoles(maxElement);

        populatePigeonHoles(array, pigeonHoles);
        collectFromPigeonHoles(array, pigeonHoles);

        return array;
    }

    /**
     * Checks if the array contains any negative integers.
     *
     * @param array the array to be checked
     * @throws IllegalArgumentException if any negative integers are found
     */
    private static void checkForNegativeInput(int[] array) {
        for (final int number : array) {
            if (number < 0) {
                throw new IllegalArgumentException("Array contains negative integers.");
            }
        }
    }

    /**
     * Creates pigeonholes for sorting using an ArrayList of ArrayLists.
     *
     * @param maxElement the maximum element in the array
     * @return an ArrayList of ArrayLists
     */
    private static List<List<Integer>> createPigeonHoles(int maxElement) {
        List<List<Integer>> pigeonHoles = new ArrayList<>(maxElement + 1);
        for (int i = 0; i <= maxElement; i++) {
            pigeonHoles.add(new ArrayList<>());
        }
        return pigeonHoles;
    }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate all elements >= 0 before calling the sort.
  2. Shift values by a known offset to make them non-negative, or pick a different sort.
  3. Use Arrays.sort for signed integers when the non-negative guarantee cannot be enforced.

Example fix

// before
PigeonholeSort.sort(data);

// after
if (IntStream.of(data).anyMatch(v -> v < 0)) throw new IllegalArgumentException("negatives not supported");
PigeonholeSort.sort(data);
Defensive patterns

Strategy: validation

Validate before calling

if (IntStream.of(array).anyMatch(v -> v < 0)) throw new IllegalArgumentException("negatives not supported by PigeonholeSort");

Type guard

public static boolean isAllNonNegative(int[] a) { return IntStream.of(a).allMatch(v -> v >= 0); }

Prevention

When it happens

Trigger: Sorting an array like {3, -1, 0}; passing counts or indices that went negative; merging datasets containing negatives.

Common situations: Signed metric data; off-by-one producing a negative index; using PigeonholeSort on general-purpose integer arrays.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/0f13399f630b4d3d. Report an issue: GitHub.