Hello I have two java classes "List" and "ListPlayground". The problem is i can´t override the toString() Method, because I get this Error:
error: toString() in List cannot override toString() in Object
public String toString() {
^
return type String is not compatible with java.lang.String
where String is a type-variable:
String extends Object declared in class List
List.java:59: error: incompatible types: java.lang.String cannot be converted to String
String string = "";
^
where String is a type-variable:
String extends Object declared in class List
Note: List.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors
Here is the class I have
public class List<String> {
private class Node {
private String element = null;
private Node next = null;
private Node(String element, Node next) {
this.element = element;
this.next = next;
}
private Node(String element) {
this.element = element;
}
}
private Node head = null;
private Node current = head;
public void prepend(String object) {
head = new Node(object, head);
}
public void append(String object) {
if(head == null) {
head = new Node(object);
return;
}
Node current = head;
while(current.next != null) {
current = current.next;
}
current.next = new Node(object);
}
public String first() {
get(0);
}
public String get(int index) {
Node current = head;
for(int i = 0; i < index; i++) {
current = current.next;
}
return current.element;
}
public int size() {
Node current = head;
int size = 0;
for(; current != null; size++) {
current = current.next;
}
return size;
}
public String toString() {
String string = "";
while(current != null) {
string += head.element + " -> ";
current = head.next;
}
return string;
}
}
Here is the ListPlayground class:
public class ListPlayground {
public static void main(String[] args) {
List<String> stringliste = new List()<>;
stringliste.append("World");
stringliste.append("!");
stringliste.prepend("Hello");
System.out.println("The Length of the List is: " + stringliste.size());
System.out.println("The first Element of the List is: " + stringliste.first());
System.out.println("The element with Index 2 is: " + stringliste.get(2));
System.out.println("The last element is: " + stringliste.get(stringliste.size() - 1));
System.out.println("The whole List is: " + stringliste.toString());
System.out.println("And again the whole List " + stringliste.toString());
}
}
can somebody help me?
I tried to debug my code but I did not succeed. I know that the class "Object" is the superclass of all classes and I have to override the toString() Method, but I do not understand why the toString() method is wrong i the List class?