主类:
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); 关于什么事情的任何想法?
答案 0 :(得分:2)
如果你得到一个NullPointerException,可能是因为你没有在你的类中初始化head变量。第一次将对象添加到LInkedLIst时,调用add方法,head为null;因此,cache = null然后您尝试在while循环中引用cache.next,这会抛出异常。
尝试将此添加到add方法的开头以处理特殊情况。
if (head == null)
head = new Node(newData, null);
else {
.. rest of method
}