2014-10-30 74 views
-1

,所以我玩弄一些代码,当我运行它,我得到这个错误,空指针异常与ArrayList的

Exception in thread "main" java.lang.NullPointerException 
    at VRSolution.findSavings(VRSolution.java:35) 
    at VRTests.main(VRTests.java:22) 

这是我的代码

public void testAlgo() { 
    this.soln = new ArrayList<List<Customer>>(); 
    int max = this.prob.depot.c; 
    int current = 0; 
    ArrayList<Customer> route = null; 
    for(Customer c:prob.customers){ 
     if(current <= max){ 
      route.add(c); 
      current += c.c; 
     } 
     else { 
      route = new ArrayList<Customer>(); 
      soln.add(route); 
     } 
    } 
} 

如果有人可以帮助我明白为什么我得到这将是非常感谢谢谢

+0

什么'prob'?你能粘贴相关的代码吗? – asgs 2014-10-30 19:27:29

+4

您正在对初始化为null的'route'变量调用'add'方法。 – 2014-10-30 19:27:47

回答

0

route.add(c);行可以在数组列表初始化之前调用。 可能这是你的问题。因此,在添加项目之前初始化路线。

0

你有这样的:

ArrayList<Customer> route = null; 

,然后这样的:

route.add(c); 

如果你试图在null引用调用一个方法,你会得到一个NullPointerException

0

通过

List<Customer> route = new ArrayList<>(); 
0

更换ArrayList<Customer> route = null;你怎么称呼它之前,初始化列表。您的案例中的路由为空,这就是您遇到异常的原因。

试试这个:

ArrayList<Customer> route = new ArrayList<>();