Home > Enterprise >  Java Beginner; Compilation Error with "endsWith" method
Java Beginner; Compilation Error with "endsWith" method

Time:01-31

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

    }
}

CodePudding user response:

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.

CodePudding user response:

You should learn what generics are. You got error because you use raw type with iterator. Raw type means Object type, but method you want to call endsWith() is the method of String type. So you should declare your iterator like Iterator<String> to specify the type of generic. So that compiler knows the actual type of objects. More about generics you can read here https://docs.oracle.com/javase/tutorial/java/generics/index.html

  •  Tags:  
  • java
  • Related