简体   繁体   English

链接列表中的Java自编程单链接列表

[英]Java Self-Programmed Singly-Linked-List in Linked-List

At least for me, I have a tricky exercise to do for university. 至少对我来说,我为大学做了一个棘手的练习。 The task is to program a singly-linked-list with all kind of methods. 任务是用各种方法编写单链表。 So far so easy, but the challenge is to store these singly-linked-lists afterwards in a Linked-List. 到目前为止这么容易,但挑战是将这些单链接列表存储在链接列表中。 In the following you see my implementation of my singly-linked-list which actually runs smoothly: 在下面你看到我的单链表的实现,它实际上运行顺利:

public class Liste {

ListenElement first;
ListenElement last;
ListenElement current;
int count;

public Liste() {
    first = null;
    last = null;
    current = null;
    count = 0;
}

// Methods...

The single-linked list consists of list elements implemented in the following: 单链接列表由以下实现的列表元素组成:

public class ListenElement {

String content;
ListenElement next;

public ListenElement(String content, ListenElement next)
{
    this.content = content;
    this.next = next;
}

//Methods...

Here is 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! 预先感谢您的帮助!

 System.out.print(zeilen.get(1)); 

//Printed: Listen.Liste@4aa298b73 instead of Hello World. //印刷:Listen.Liste@4aa298b73而不是Hello World。

That's the output of the default Object#toString . 这是默认Object#toString的输出。 If you want different output from your Liste class, you need to override toString to provide that different output. 如果您想要从Liste类中获得不同的输出,则需要覆盖toString以提供不同的输出。

For example: If you wanted Liste#toString to return a comma-delimited list of the toString s of its contents: 例如:如果您希望Liste#toString返回其内容的toString的逗号分隔列表:

@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'm making assumptions there about how your list class works, based on the code you showed...) (我根据你展示的代码在那里假设你的列表类是如何工作的......)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM