I’m a beginner in Java and am kinda confused why the below code outputs a compilation error.
Below is the code.
What did I do wrong?
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = List.of("Apple", "Bat", "Cat");
// System.out.println("Apple".endsWith("le"));
Iterator it = words.iterator();
while (it.hasNext()) {
if (it.next().endsWith("at")) {
it.remove();
}
}
}
}
>Solution :
You need to declare your iterator as Iterator<String> to tell the compiler it.next() will return a String, which has the endsWith, otherwise it will think it.next() will return an Object, which does not have endsWith.