0
whats the problem?
the purpose of this code is to remove all the unEven numbers (numbers that dont divide well by 2). why isn't it working? (im not saving the code and sending a link because the code is pretty short so its not neccesary... Sorry about that...) code: import java.util.*; public class Main { public static void main(String[] args) { List<Integer> l = new ArrayList<Integer>(); l.add (12); l.add (3); l.add (2); l.add (5); l.add (8); Collections.sort(l); for (int fe : l){ if (fe % 2 != 0){ l.remove (fe); } System.out.println(fe); } } }
3 Réponses
+ 3
Hello yahel
Removing elements while iterating over a list or array will always leads to troubles.
Here you can read more about this exception: https://www.baeldung.com/java-concurrentmodificationexception
The simpliest way to avoid this exception is to use removeIf()
l.removeIf(i -> i % 2 != 0);
System.out.println(l);
If you are not familiar with lambda expressions: http://tutorials.jenkov.com/java/lambda-expressions.html
You can also look here for other techniques: https://stackoverflow.com/questions/10431981/remove-elements-from-collection-while-iterating
+ 1
You may want to read this ,
https://www.geeksforgeeks.org/remove-element-arraylist-java/amp/
+ 1
Thanks!