Java Self-Programmed Single-Linked-List to Linked-List
At least for me, I have a difficult exercise for the university. The challenge is to program a singly linked list with all types of methods. So simple so far, but the challenge is to save these separately linked lists later in the Linked-List. Below you can see my implementation of my singly linked list, which works fine:
public class Liste {
ListenElement first;
ListenElement last;
ListenElement current;
int count;
public Liste() {
first = null;
last = null;
current = null;
count = 0;
}
// Methods...
A singly linked list consists of list items, implemented as follows:
public class ListenElement {
String content;
ListenElement next;
public ListenElement(String content, ListenElement next)
{
this.content = content;
this.next = next;
}
//Methods...
Here's my problem:
LinkedList<Liste> zeilen = new LinkedList<>();
Liste zeile1 = new Liste();
Liste zeile2 = new Liste();
zeile1.addBehind("Hello");
zeile1.addBehind("World");
zeile2.addBehind("Hello");
zeile2.addBehind("World");
zeilen.add(zeile1);
zeilen.add(zeile2);
System.out.print(zeilen.get(1));
//Printed: Listen.Liste@4aa298b73 instead of Hello World.
Thank you in advance for your help!
source to share
System.out.print(zeilen.get(1));
// Printed: Listen.Liste@4aa298b73 instead of Hello World.
This is the default output Object#toString
. If you need different output from your class Liste
, you need to override toString
to provide that different output.
For example: If you want to Liste#toString
return a toString
comma-delimited list of it:
@Override
public String toString() {
StringBuffer sb = new StringBuffer(10 * this.count); // Complete guess
ListenElement el = this.first;
while (el != null) {
sb.append(el.content.toString());
el = el.next;
if (el != null) {
sb.append(", ");
}
}
return sb.toString();
}
(I am making assumptions about how your list class works based on the code you showed ...)
source to share