2

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

}
2
  • 3
    Never ever use pre-defined class names as your own class name. Commented Jan 21, 2013 at 18:10
  • OK thank you! i realise that now :D Commented Dec 13, 2013 at 22:31

2 Answers 2

11

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);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

OP, make sure to close input too. (NEVERMIND)
@jsn.. that is really not needed.
@RohitJain, never mind, you are right. You shouldn't close System.in.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.