0

Sorry if this has been asked before, but I haven’t been able to find anything that’s been helpful. Basically, when I add a bunch of characters to an ArrayList, and then try removing one of the characters, I get an IndexOutOfBoundsException, and I don’t understand why. Here's sort of a general example of what I am talking about.

public void addChars(){
    ArrayList<Character> chars = new ArrayList<Character>();
    word = "hello";
    chars.add(word.charAt(0));
    chars.add(word.charAt(1));
    chars.add(word.charAt(2));
    chars.add(word.charAt(3));
    chars.add(word.charAt(4));

    chars.remove(word.charAt(1));
}

which gives the following error

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 101, Size: 5
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.remove(ArrayList.java:492)
at trial.addChars(trial.java:26)
at trial.main(trial.java:31)

I don't understand how I can be getting an IndexOutOfBoundsException when I'm trying to remove a character, shouldn't java look through my ArrayList "chars", and either remove or not remove depending on if the character is present?

If I alter this code to remove a character that is not present in my ArrayList it works fine, it is only when I try removing a character that is in the ArrayList that things break down.

Thanks!

John
  • 1

1 Answers1

1
chars.remove((Character)word.charAt(1));

The ArrayList.remove() method can also take an integer index. Try:

chars.remove(chars.indexOf(word.charAt(1)));    
Teddy Koker
  • 754
  • 5
  • 8