简体   繁体   中英

java.lang.NullPointerException on ArrayList

I have the following code:

for (int i=0; i<wallMaterialName.size(); i++){
if (Math.abs(calculatedWallUValue - alternativeWallUValue) > 0.01){
   if(wallMaterialName.get(i).charAt(0) == 'A'){                   //*****ERROR IN HERE*****
      PreparedStatement prepStateMat = con.prepareStatement("select * from concretestonefloor where value<? order by value desc limit 1");
      prepStateMat.setFloat(1, (Float)wallMaterialLambda.get(i));
      ResultSet rsMaterial = prepStateMat.executeQuery();
      //...
      }
  //...
  }
}

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

if(wallMaterialName.get(i).charAt(0) == 'A')

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.

The array list is not empty, otherwise you'd get an index out of bounds exception (which is impossible to produce in your code, because your loop checks i < wallMaterialName.size() ). However, your array list contains a null object at index i .

Change your code as follows to fix the error:

String materialName = wallMaterialName.get(i);
if(materialName != null && materialName.charAt(0) == 'A') ...

If the list were empty, you wouldn't get the error. The arraylist in fact contains elements, but the elements are null and that's how you end up with your NullPointerException . If you demonstrate code that fills the list, I may be able to help you further.

On a separate note: don't iterate through the list by indexing: use the enhanced for syntax:

for (String element : wallMaterialName) ...

This will at least eliminate your worries about iterating over a non-existent element. The way you use the same index for two parallel lists shows that your design has potential to improve in that respect as well. You should have a single list of custom objects that contain both the strings from the first list and the floats from the second.

your arraylist wallMaterialName has a null value at some index i. to know at what index you have null value do the below test.

for(int i=0; i<al.size(); i++){
            if(al.get(i)==null){
                System.out.println(i);
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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