2014-03-25 102 views
1

我有一个数组列表与多个LinkedList对象。我的主要代码:ArrayList toString()方法

import java.io.*; 
import java.util.AbstractList; 
import java.util.*; 

public class Sort { 
public static void main (String[] args){ 
    int listNum = 0; 
    File file = new File("input.txt"); 

    ArrayList<LinkedList> my_lists = new ArrayList<LinkedList>(); 

    try { 
     Scanner sc = new Scanner(file); 
     while (sc.hasNextLine()) { 

      System.out.println("List" + listNum); 
      String line = sc.nextLine(); 
      LinkedList the_list = new LinkedList(); 
      String[] templist = line.split("\\s*,\\s*"); 

      for(int i=0; i<templist.length; i++){ 
       String temp = templist[i]; 
       the_list.add(temp); 
       System.out.println(temp); 
      } 
      listNum++; 
      my_lists.add(the_list); 


     } 
     sc.close(); 
    } 
    catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 

    for(int i=0;i<my_lists.size();i++){ 
     System.out.println(my_lists.get(i).toString()); 
     } 
    } 

} 

这里是我的LinkedList对象类:

package kruskal; 
import java.util.AbstractList; 

public class LinkedList { 

Node head; 

public LinkedList(){ 
    this.head = null; 
} 

public void add (Object newData){ 
    Node cache = head; 
    Node current = null; 

    if (cache == null) 
     current = new Node(newData, null); 
     else { 


    while ((current = cache.next) != null) 
     cache = cache.next; 

    cache.next = new Node(newData,null); 
     } 
} 



public Object getFront(){ 
    return this.head.data; 
} 

} 

我的节点类:

package kruskal; 

public class Node { 
public Object data; 
public Node next; 

public Node(Object data,Node next){ 
    this.data=data; 
    this.next=next; 
} 
} 

在我的代码主要部分的结束,我想做一个for循环来显示我的ArrayList中的每个LinkedList,但我只能得到LinkedList的地址:

[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 

任何想法为什么我的toString()方法不工作?我假设我需要LinkedList类中的方法,但是我会返回什么?

+0

因为你还没有重写'LinkedList'类中的'toString'方法。 –

回答

5

问题是你没有LinkedList类中定义的toString()方法,所以它继承了the toString() method from Object,它负责你看到的输出。

换句话说,该方法返回一个字符串等于值:在LinkedList

getClass().getName() + '@' + Integer.toHexString(hashCode()) 

覆盖toString()并返回String你想看到打印出来。

+0

我希望能够返回包含在我的ArrayList(my_lists [i])中的指定的(i)LinkedList。我只是简单地返回my_lists [i]? – mickdeez

2

你需要覆盖toString方法你的LinkedList
你可以做如下:

@Override 
public String toString() { 
    String res = "["; 
    Node current = this.head; 
    while(current != null) { 
     res += current.toString() + "\t"; 
     current = current.next; 
    } 

    res += "]"; 
    return res; 
} 

当然...你会那么必须覆盖Node#toString为好;)

示例代码:

@Override 
public String toString() { 
    return data.toString(); 
} 
+0

我现在得到一个空指针异常。我的输出是否仍然需要System.out.println(my_lists.get(i).toString()); ? – mickdeez

+0

是的,你应该继续使用这个电话!我的代码中有些东西实际上是错误的。我刚刚更新了我的答案。你可以试试这个新版本吗? – 2014-03-25 23:03:24