简体   繁体   中英

Remove an object n times from array list in JAVA

Alright, I'm making a method that should be able to remove objects from an array list through the use of a string input.

Say I want to remove the following numbers: {1,2,4,3,3,1} from an arraylist. How can I ensure that it only removes 1 & 3 twice and 4 & 2 once?

What I have is:

mv.displayMessages("choosedicestokeep");
String in = mv.getInput();

for (char c : in.toCharArray()) {
    int x = Character.getNumericValue(c);
    for (Iterator<Integer> it = rollingHand.iterator(); it.hasNext(); ){
    int i = it.next();
        if (x == i) {
        finalHand[finalArrIndex] = i;
        it.remove();
        finalArrIndex++;
    }
}
}

But this checks the arraylist "RollingHand" and removes ALL instances of a number and not the number of times I write a number which is what I want.

So if i enter {1,1,1,2,2,4} it should remove three 1s, two 2s and one 4.

https://stackoverflow.com/users/4584292/mike Solved the obvious answer.

Breaking to a statement outside the inner loop solved the problem.

The method doesn't return anything because it sets a private int[] finalHand in the class which is later accessed by other methods.

All cred to Mike!

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