Plaix
Plaix

Reputation: 881

Error using ArrayList in Java

I was solving a problem before including it in my code and using List to get strings then work around with them. I got the error: "type List does not take parameters List words = new ArrayList();" after compilation. I searched but the syntax i use is correct, please whats wrong with the code?

import java.util.Scanner;
import java.util.ArrayList;

public class List{
    public static void main(String args[]){
        List<String> words = new ArrayList<String>();
        Scanner input = new Scanner(System.in);
        for (int i=0; i < 3; i++)
            words.add(input.nextLine());
        System.out.println(words);
    }

}

Upvotes: 2

Views: 6632

Answers (2)

Pablo
Pablo

Reputation: 3673

Try this:

import java.util.Scanner;
import java.util.ArrayList;

public class List{
    public static void main(String args[]){
        java.util.List<String> words = new ArrayList<String>();
        Scanner input = new Scanner(System.in);
        for (int i=0; i < 3; i++)
            words.add(input.nextLine());
        System.out.println(words);
    }

}

Your class is called List. So by default, it is assumed that the List you declared refers to your class.

It would be better to avoid names like List for your classes.

Upvotes: 0

Perception
Perception

Reputation: 80603

This is one of the reasons you should use unique names for your own classes. You are really meaning to use java.util.List, but since you called your class List as well, the real problem is masked. Rename your class and add the import for java.util.List to fix the issue:

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

public class MyClass{
    public static void main(String args[]){
        List<String> words = new ArrayList<String>();
        Scanner input = new Scanner(System.in);
        for (int i=0; i < 3; i++)
            words.add(input.nextLine());
        System.out.println(words);
    }
}

Upvotes: 11

Related Questions