0
votes

I'm learning the java collection framework and unable to figure out what is actually causing the error and here I'm using eclipse 4.18.0 and java version 15. There is some problem in the setup because the code is working fine in vs code.

package lists;
import java.util.ArrayList;
import java.util.List;
public class ArrayListCreate {
    public static void main(String[] args) {    
        List<String> fruits=new ArrayList<>();
        fruits.add("Apple");
        System.out.println(fruits);
    }
}

Error : Exception in thread "main" java.lang.Error: Unresolved compilation problems: List cannot be resolved to a type ArrayList cannot be resolved to a type

at lists.ArrayListCreate.main(ArrayListCreate.java:6)

1
List<String> fruits=new ArrayList<>(); You need to specify the type of list to be created or use diamond operator - Rohan Kumar
Still there is error - Neha Maurya
Something is weird here, as Matthew pointed out, compiler is complaining about error on lists.ArrayListCreate.main(ArrayListCreate.java:21) . But your file does not seem to be having even 10 lines. Are you sure you've shared complete file with us? - Rohan Kumar
Please see the updated Question - Neha Maurya
I tried your updated code in my IntelliJ with jdk 1.11 and it seems to be building fine. I think there is some problem in your setup - Rohan Kumar

1 Answers

0
votes

When instantiating generic classes you need to include the generic in the actual instantiation like List<String> fruits = new ArrayList<String>();.

That's actually a lie since you can make it simpler by just doing List<String> fruits = new ArrayList<>();. You can do this because it can infer the generic type from the left side of the line.