Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Beginner; Compilation Error with "endsWith" method

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading