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); } } }

7th Jul 2020, 7:55 PM
Yahel
Yahel - avatar
3 Respostas
+ 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
7th Jul 2020, 8:27 PM
Denise Roßberg
Denise Roßberg - avatar
7th Jul 2020, 8:16 PM
Abhay
Abhay - avatar
+ 1
Thanks!
8th Jul 2020, 8:20 PM
Yahel
Yahel - avatar