Why my IF can’t get some of my ArrayList’s indexes?

Tags: ,



My idea here is to check whether the elements of my ArrayList start with A, B, C, or with another letter, but for some reason, my IF can’t get some words, such as “Almofada”.

package ArrayLists;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

public class ArrayList2 {
    public static void main(String[] args) {
        //arraylist pra verificar quais strings começam com a,b,c
        ArrayList<String> words = new ArrayList<>(
        Arrays.asList(
        "Canivete",
        "Almofada",
        "Corda",
        "Parede",
        "Caixa",
        "Zilhão",
        "Dedo"  
        ));

        ArrayList abc = new ArrayList<>();
        ArrayList rest = new ArrayList<>();

        for(int i = 0; i < words.size();i++){
            char firstChar = words.get(i).charAt(0);
            if(firstChar == 'A'||firstChar == 'B'||firstChar == 'C'){
                abc.add(words.get(i));
                words.remove(words.get(i));
            }else{
                rest.add(words.get(i));
                words.remove(words.get(i));
            }
        }
        System.out.println("Start with A,B or C: " + abc);
        System.out.println("Start with other letters: " + rest);
        System.out.println("Original array: " + words);
    }
}

Output

Start with A,B or C: [Canivete, Corda, Caixa]
Start with other letters: [Dedo]
Original array: [Almofada, Parede, Zilhão]

Answer

Your issue is with your for loop. You are incrementing the index ‘i’ on each iteration of the loop, then removing the word at words(i). Because i gets incremented, but the size of the words list is reduced each iteration, ‘i’ quickly increases to the new size of the words list without actually evaluating the Strings at the end.

To correct, you simply need to avoid incrementing i on each iteration:

for(int i = 0; i < words.size();){ //Notice i is not being incremented (i++)
    char firstChar = words.get(i).charAt(0);
    if(firstChar == 'A'||firstChar == 'B'||firstChar == 'C'){
        abc.add(words.get(i));
    }else{
        rest.add(words.get(i));
    }
    words.remove(words.get(i));
}


Source: stackoverflow