Reputation: 3009
I'm getting an error when trying to create the linked list that says:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The type LinkedList is not generic; it cannot be parameterized with arguments <String>
at LinkedList.main(LinkedList.java:7)
Anyone know how to fix this error? Here is the program:
import java.util.*;
public class LinkedList {
public static void main(String[] args) {
List<String> list = new LinkedList<String>();
Scanner input = new Scanner(System.in);
System.out.print("How many elements do you want to add: ");
int num = input.nextInt();
for(int i = 0; i < num; i++) {
System.out.print("Add Element: ");
String element = input.next();
list.add(element);
}
System.out.println();
System.out.println("LinkedList elements are: ");
for(int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
Upvotes: 6
Views: 12599
Reputation: 120516
Change
new LinkedList<String>()
to
new java.util.LinkedList<String>()
The source of the problem is that LinkedList
refers to the class containing the code class LinkedList
, not java.util.LinkedList
.
Unqualified class names like LinkedList
(in contrast to "fully-qualified names" like java.util.LinkedList
) are resolved by looking for a match in a certain order. Roughly
Section "6.5 Determining the Meaning of a Name" of the Java language specification explains in more detail.
Upvotes: 18
Reputation: 36703
Your class is also called LinkedList so it conflicts. If you want to fix it use this line instead. Better still, just have a different name for your class...
List<String> list = new java.util.LinkedList<String>();
Upvotes: 4
Reputation: 78650
public class LinkedList {
Your class is not defined as generic. I think though that you are trying to use Java's LinkedList, so you should rename your class.
Upvotes: 3
Reputation: 54242
public class LinkedList {
You named your own class LinkedList
, so it's taking precedence over the java.util.LinkedList
.
Either change the name of the class to something else or do new java.util.LinkedList<String>()
to make it explicit which one you want.
Upvotes: 1
Reputation: 14458
You placed your main
method in a class called LinkedList
, which takes precedence over the built-in LinkedList
class in the compiler's name resolution algorithm. In other words, because your main
method is inside a class called LinkedList
, the compiler takes the name LinkedList
to mean your LinkedList
class instead of java.util.LinkedList
. There are two easy fixes:
Instead of writing
List list = new LinkedList();
write
List list = new java.util.LinkedList();
I highly recommend the first option. Since your LinkedList
class doesn't actually represent the linked list data structure, the name on your class is confusing to someone reading the code. Maybe call your class LinkedListTest
instead i.e. your file could be
import java.util.*;
public class LinkedListTest {
// Implementation of main and helper methods
}
Upvotes: 2