-1

My application crashes because of this method. Please help :=)

public void sortedList() {
    String goodLetter = "B";

    for (String myItem : myArrayList) {
        String myFirstChar = myItem.substring(0, 1);
        if (myFirstChar != goodLetter) {
            myArrayList.remove(myItem);
        }
    }
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Killian
  • 73
  • 1
  • 9

2 Answers2

3

Your code will crash if:

  • myArrayList contains a null element (NullPointerException)
  • myArrayList contains the empty String (IndexOutOfBoundsException)
  • Any element from myArrayList does not start with "B" (ConcurrentModificationException)

For that last, and most probable, cause see the question linked by @Todd in the comments.

Additionally, in Java you should compare Strings using .equals instead of == or !=.

RobCo
  • 6,240
  • 2
  • 19
  • 26
  • You could consider immediately switching over to [Kotlin](https://kotlinlang.org/docs/reference/), where once again it is fine to compare Strings using `==` ;) – RobCo Jan 16 '19 at 16:18
  • Exactly because of the bug in string comparison it will probably crash with a word that does start with `B` too. – Ole V.V. Jan 16 '19 at 16:55
0

First, for string comparison, use String.equals() and not ==. Second, if you want to remove objects from a list :

  • do a reverse browsing
  • or create an intermediary array containing objects to remove
Bruno
  • 3,872
  • 4
  • 20
  • 37