Home > Software engineering >  How to remove elements from an ArrayList?
How to remove elements from an ArrayList?

Time:10-14

        ArrayList<Rolling> copy = new ArrayList<Rolling>();
        for (int i = 0; i < sequence.size(); i  ) {
            copy.add(sequence.get(i));
        }

        ListIterator<Rolling> listIterator = copy.listIterator();

        // Remove each element one by one
        for (int j = 0; j < copy.size(); j  ) {
            listIterator.next();
            if (copy.contains()) {
                listIterator.remove();

            }
        }
    public static void main(String[] args) {
      remove(sequenceOfDice(4), 4);

    }
}

short summary: I have a class called Rolling and I wanna thru this method copy its elements and then remove the value of n from the new list and return the rest but I am not geting far since i got a couple of errors.

The error I get is:The method contains(Object) in the type ArrayList is not applicable for the arguments ()

CodePudding user response:

the method "copy.contains()" should have a parameter(argument). that means,you should write like this "copy.contains(x)"

what's more, i think you are a new learner.because your code have many errors or sames strange.

your comment is "// Remove each element one by one" but you said "then remove the value of n from the new list", is this conflict?

CodePudding user response:

please paste all the code and compile it successfully on your laptop.

By the way, in a for loop, we usually use iterator to remove element because remove element will cause modcount change,try below code:

while(listIterator.hasNext()){
    Rolling next = listIterator.next();
    if (copy.contains(next)) {
        listIterator.remove();
    }
}
  • Related