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));
}
}
}
The elements are not indexed, so random access like an array is not possible. Instead, we traverse from the beginning of the list and access the elements. In Java, the LinkedList class is the doubly-linked list implementation of the List and Deque interfaces. The LinkedList class is present in the java.
LinkedList. set() method is used to replace any particular element in the linked list created using the LinkedList class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() method.
Java provides a built LinkedList class that can be used to implement a linked list. In the above example, we have used the LinkedList class to implement the linked list in Java. Here, we have used methods provided by the class to add elements and access elements from the linked list.
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.
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>();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With