• Post Reply Bookmark Topic Watch Topic
  • New Topic

java.lang.NullPointerException on ArrayList  RSS feed

 
Iman Paryudi
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following code:


When I run the code, a "java.lang.NullPointerException" appear.
The error comes from this code:

I don't know why the arraylist is empty since I have checked that it contains some data. Anybody knows how to solve this problem? Thanks.
 
naved momin
Ranch Hand
Posts: 692
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
before using this you should always check for null
wallMaterialName.get(i).charAt(0)


like
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not necessary to get it as an Object and cast it to a String; you can just do:
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
naved momin wrote:before using this you should always check for null
wallMaterialName.get(i).charAt(0)



No, that's not true. We shouldn't have to put a lot of null checks in our code. That just leads to clutter. There's such a thing as too much defensive coding. In most cases it's best just to document what a method requires, and then assume those preconditions have been met. If the caller is careless enough to pass null, he gets an NPE, and that is appropriate.

For example, in this case, the only way he's getting an NPE there is if he put a null value into the list. That's probably the real bug, and it would be better to fix that then to work around it with a null test. (It's possible that it's not a bug--that null has a particular meaning in his list. That seems rather unlikely though, and if it is true, may be a sign of bad design.)
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Iman Paryudi wrote:
I don't know why the arraylist is empty since I have checked that it contains some data. Anybody knows how to solve this problem? Thanks.


It's not empty. It has at least one null element in it, because you put it there.

Also you should not uset get() to iterate over a List. Use a foreach loop or an explicit Iterator.

http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
http://docs.oracle.com/javase/tutorial/collections/index.html
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!