猿问

LinkedList对象如何使用Syso输出内容?

我已经编写了一小段代码来实现链接列表数据结构。我有一个内部类“节点”,其中有两个字段“节点”和“值”。链表的构造方法接受int值参数,并将该值分配给Node对象,然后将Node对象添加到该LinkedList对象。


我的问题是java.util.LinkedList的哪个代码使列表对象被打印为数字列表,而不是其对象的地址?


当我打印“ list1”时,输出为[3,4]。当我打印“列表”时,输出是对象地址的哈希码。


我toString()在java.util.LinkedList课堂上没找到。


如何制作代码以打印LinkedList的内容?


下面是代码:


class LinkedList {


    Node first;


    Node getNode(){

        return new Node();

    }


    class Node{

        Node next;

        int value;

    }


    void add(int value){

        Node n=this.getNode();

        n.value=value;

        n.next=null;


        if (first==null){

            first=n;

        } else{

            first.next=n;

        }

    } 

}

public class LinkedListTest{

    public static void main(String[] args) {

        LinkedList list=new LinkedList();

        java.util.LinkedList<Integer> list1=new java.util.LinkedList<>();

        list1.add(3);

        list1.add(4);

        list.add(1);

        list.add(2);

        System.out.println(list);

        System.out.println(list1);

    }

}


回首忆惘然
浏览 219回答 2
2回答

元芳怎么了

您的类LinkedList(建议您重命名它,因为它可能与混淆java.util.LinkedList)需要重写method Object::toString,该方法在打印到控制台中被调用。我在java.util.LinkedList类中没有找到toString()。有点侦探性的工作-您必须单击LinkedList<E>扩展的源代码,然后再扩展AbstractSequentialList<E>,AbstractList<E>最后扩展AbstractCollection<E>(源代码)类,在该类中,重写的Object::toString方法负责所有元素的类似于字符串的表示形式。在那里您可以得到启发。如何制作代码以打印LinkedList的内容?这条路:@Overridepublic String toString() {&nbsp; &nbsp; StringBuilder sb = new StringBuilder("[");&nbsp; &nbsp; if (first != null) {&nbsp; &nbsp; &nbsp; &nbsp; Node temp = first;&nbsp; &nbsp; &nbsp; &nbsp; String sep = "";&nbsp; &nbsp; &nbsp; &nbsp; while (temp != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(sep).append(temp.value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp = temp.next;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sep = ", ";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return sb.append(']').toString();}

湖上湖

例如,您必须创建自己的toString方法class LinkedList {&nbsp; &nbsp; //...&nbsp; &nbsp; @Override&nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; &nbsp; StringBuilder text = new StringBuilder("[");&nbsp; &nbsp; &nbsp; &nbsp; String del = "";&nbsp; &nbsp; &nbsp; &nbsp; if (first != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; text.append(del).append(first.value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; first = first.next;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; del = ", ";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } while (first != null);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; text.append(']');&nbsp; &nbsp; &nbsp; &nbsp; return text.toString();&nbsp; &nbsp; }}如果再次运行代码,则输出[1, 2]
随时随地看视频慕课网APP

相关分类

Java
我要回答