【问题标题】:Adding values to LinkedList class向 LinkedList 类添加值
【发布时间】:2014-03-20 13:35:27
【问题描述】:

主类:

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

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

            String line = sc.nextLine();
            LinkedList the_list = new LinkedList();
            String[] templist = line.split("\\s*,\\s*");

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

            my_lists.add(the_list);
            System.out.println(line);
        }
        sc.close();
    } 

从我的 LinkedList 类中添加方法:

    public void add (Object newData){
    Node cache = head;
    Node current = null;
    while ((current = cache.next) != null)
        cache = cache.next;

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

每次我为该行运行它时都会出现错误:the_list.add(temp); 有什么想法吗?

【问题讨论】:

  • 返回的具体错误/堆栈跟踪是什么?

标签: java arrays list linked-list add


【解决方案1】:

如果您收到 NullPointerException,可能是因为您尚未在类中初始化 head 变量。第一次向 LInkedLIst 添加 Object 时,调用 add 方法并且 head 为 null;因此,cache = null 然后您尝试在 while 循环中引用 cache.next,这会引发异常。

尝试将此添加到 add 方法的开头以处理特殊情况。

if (head == null)
head = new Node(newData, null);
else {
  .. rest of method 
}

【讨论】:

  • 我的代码顶部有这个,只是没有复制到 stackexchange。我将它移到循环的开头,但仍然存在相同的错误。我很确定它在 the_list.add(temp; line
  • 什么是完整的异常/堆栈跟踪?
  • 是的。如果他们最好地回答了您的问题,请记住也接受答案。
  • 完成 :) 只需要等待计时器
猜你喜欢
  • 2018-06-24
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多