开发者

A NullPointerException in the code

When I am trying to execute the 开发者_如何学Gocode below, in the project it gives an error manual array copy to collection. On the other hand, when I execute the project in the JSP using NetBeans, it is showing NPE at a for-loop. Any idea?

ArrayList courseNames=new ArrayList();

String []values=request.getParameterValues("ToList");

for(int i=0;i<values.length;i++)
    courseNames.add(values[i]);


Do you check that the value in values is not null? You should do that, as getParameterValues isn't guaranteed to return non-null in all cases. (In particular, it's not safe to assume that if ToList is absent, you'll get an empty array.)


Edit: The best way to do this is to do:

ArrayList<String> courseNames = new ArrayList<String>();     // Java5 good style
String[] values = request.getParameterValues("ToList");      // General style

if (values != null)                                          // No crashes
    courseNames.addAll(Arrays.asList(values));               // Implicit loop

Alternatively, use a higher level framework (e.g., Apache CXF) to unpack the values from the request, but that's a much bigger job for you to do since they involve writing your code in quite a different way to before.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜