I want to do something simple which is create my own list class that is based on java.util.linkedlist but i want to limit what can be done. Lets just say that for now, the only method I want available is the addFirst method. I’m creating somewhat of a singly linked list. The issue i’m having is that addFirst doesnt seem to be recognized and i’m not sure if i’m creating the list properly inside my own constructor. Here is the code I have so far.
import java.util.LinkedList;
public class singleList {
singleList() {
new LinkedList();
}
// void add(name addName) {
// addFirst(addName);
// }
public static void main(String[] args) {
singleList nameList = new singleList();
name name1 = new name("John", "Smith");
nameList.add(name1);
System.out.println("LinkedList contains : " + nameList);
}
}
So as you can see what I want to do is create a list called nameList and at this point, the ONLY thing it can do is use the add method, which should call the LinkedList’s addFirst method which adds the element to the first position in the list. Does this make sense?
The first error I get is that it cannot find the symbol “addFirst” from my add method and i’m also not sure if my constructor for singleList is correct.
In case anyone is wondering, this is for a school assignment.
Here is the revised code, which I took some advise from the first answer here which looks similiar to another.
public class SingleList {
private LinkedList internalList;
SingleList() {
internalList = new LinkedList();
}
void add(name addName) {
internalList.addFirst(addName);
}
String get(int index) {
return internalList.get(index).toString();
}
public static void main(String[] args) {
SingleList nameList = new SingleList();
name name1 = new name("John", "Smith");
nameList.add(name1);
String getter = nameList.get(0);
System.out.println("LinkedList contains : " + nameList.get(0));
}
}
The problem with the code you posted is that you aren’t assigning the
LinkedListto anything, then theaddFirst()method is written as if it’s a static method of thesingleListclass, which doesn’t exist. What I believe you were trying to do is:This also has the benefit of generics, which means it can use any type which
LinkedListcan use. Additionally, I took the liberty of changing the case of the class name, as the Java standard is to use proper cases on Class names, and sulking case on variables.