Search code examples
javaindexoutofboundsexceptionminecraftbukkit

Array.length & ArrayIndexOutOfBoundsException


I excluded a large portion of the code that was irrelevant to the issue. Below is the code for a Bukkit plugin -- everything below is defined. However, when the code attempts to go through the second if statement (where I attempt to compare the length), it throws ArrayIndexOutOfBoundsException.

I have compared exempt.length to 0 and printed the result, which gave true, so I'm not sure why the comparison is producing an error.

public Player[] exempt = { }; // If exempt is defined as a new Player[100], it will result in NullPointerException.

if (args[0].equalsIgnoreCase("toggle")) {
    boolean isExempt = false;

    if (exempt.length > 0) {
        for (Player player : exempt) {
            if (player.getName().equals(commandSender.getName())) {
                isExempt = true;
            }
        }
    }

    if (!isExempt) {
        exempt[exempt.length] = (Player) commandSender; // ArrayIndexOutOfBoundsException
    }

    commandSender.sendMessage(ChatColor.GREEN + "Toggled receiving AdminChat to " + (!isExempt ? "true" : "false") + ".");
    return true;
}

Solution

  • You cannot access exempt[exempt.length].

    Since indices are allocated from 0 to exempt.length-1.

    What's more, that line should also be inside the "if (exempt.length > 0)" block, as it will give an exception too when the array is empty. Because exempt.length == 0, but exempt.length == -1

    Thanks for Aimert's suggestion.