1 public class TestToString { 2 public static void main(String[] args){ 3 Node node1=new Node("東邪"); 4 node1.next=new Node("西毒"); 5 node1.next.next=new Node("南帝"); 6 node1.next.next.next=new Node("北丐"); 7 node1.next.next.next.next=new Node("中神通"); 8 System.out.println(node1);//打印一個對象即調用該對象的toString()並打印出toString()返回值 9 } 10 } 11 class Node{ 12 Object value; 13 Node next; 14 public Node(Object value){ 15 this.value=value; 16 } 17 public String toString(){ 18 return next==null?value.toString():value+","+next;//對象和String類型作+操作是返回對象的toString 19 } 20 }
運行結果:
東邪,西毒,南帝,北丐,中神通
