向LinkedList类添加值

米克德兹

主类:

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); 有什么想法吗?

史蒂文·马斯坦德里亚

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章