简体   繁体   English

向LinkedList类添加值

[英]Adding values to LinkedList class

Main Class: 主类:

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();
    } 

Add method from my LinkedList class: 从我的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);
}

It's giving me an error everytime I run this for the line: the_list.add(temp); 每次我为这行运行时都会给我一个错误:the_list.add(temp); Any ideas on what's going on? 关于发生了什么的任何想法?

If you're getting a NullPointerException, it probably because you haven't initialized the head variable in your class. 如果你得到一个NullPointerException,可能是因为你没有在你的类中初始化head变量。 The first time you go to add an Object to your LInkedLIst, you call the add method and head is null; 第一次将对象添加到LInkedLIst时,调用add方法,head为null; Thus, cache = null and you then try to reference cache.next in the while loop, which throws an Exception. 因此,cache = null然后您尝试在while循环中引用cache.next,这会抛出异常。

Try adding this to the beginning of your add method to handle the special case. 尝试将此添加到add方法的开头以处理特殊情况。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM