简体   繁体   中英

Add sublists to ArrayList with for loop

I'm trying to make a method that removes all words within the alphabetical range of two strings. The parameters I've given should remove basically everything, but this is my output:

[and, my, friends]

I really don't understand why???

public static void main(String[] args) {
        ArrayList<String> stringList = new ArrayList<String>();
        stringList.add("hello");
        stringList.add("and");
        stringList.add("welcome");
        stringList.add("my");
        stringList.add("little");
        stringList.add("friends");
        System.out.println(stringList);
        removeInRange(stringList, "abc", "zen");
    }

    public static void removeInRange(ArrayList<String> arrayList, String start, String end) {
        char startChar = start.charAt(0);
        char endChar = end.charAt(0);
        for (int i = 0; i < arrayList.size(); i++) {
            Character target = arrayList.get(i).charAt(0);
            for (char c = startChar; c <= endChar; c++) { 
                if (target.equals(c)) {
                    arrayList.remove(i);
                }
            }
        }
        System.out.println(arrayList);
    }

When you remove an element from an ArrayList, all the indices of the elements following it are decremented by one. You have to account for that in your loop :

For example:

    for (int i = 0; i < arrayList.size(); i++) {
        Character target = arrayList.get(i).charAt(0);
        for (char c = startChar; c <= endChar; c++) { 
            if (target.equals(c)) {
                arrayList.remove(i);
                i--; // this would make sure you don't skip any element in the list
            }
        }
    }

You want to go through the list backwards. I won't tell why for now in case you want to figure it out on your own ... If you can't, ask :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM