I try to remove all the person under 18 years old from my list, so i have a class Person and this is what i tried in my Main:
import java.util.*;
public class Main {
public static void main(String[] args) {
Person person1 = new Person("Victor", 28, "meerdonk");
Person person2 = new Person("Alex", 17, "antwerpen");
Person person3 = new Person("Vlad", 15, "mechelen");
List<Person> listOfPersons = List.of(person1, person2, person3);
List<Person> adults = getLessThen18(listOfPersons); **//line 22**
System.out.println(adults);
}
public static List<Person> getLessThen18(List<Person> personList) {
for (Iterator<Person> iterator = personList.listIterator(); iterator.hasNext();){
if (iterator.next().getAge() < 18 ) {
iterator.remove(); **//line 40**
}
}
return personList;
}
}
So I try to iterate trough the list of persons and then if the person is under 18 to remove it. As i run the code i get this output :
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
at java.base/java.util.ImmutableCollections$ListItr.remove(ImmutableCollections.java:380)
at victor.Main.getLessThen18Iteration(Main.java:40)
at victor.Main.main(Main.java:22)
Can someone please let me know what I did wrong?