简体   繁体   English

java.lang.NullPointerException如何修复

[英]java.lang.NullPointerException how to fix

This is an example of connection pool. 这是连接池的一个示例。 I think I've initialized all objects, but I get the null pointer exception. 我想我已经初始化了所有对象,但是我得到了空指针异常。 How can I fix the problem? 我该如何解决该问题?

package hello;

public class C {

 public  static void  main(String[] args) {
     CConnectionManager con=new CConnectionManager();
     CConnection conn=new CConnection();
     conn=con.GetConnection();

 }

 public static class CConnectionManager {
  private static final int MaxConSize=10;
  private CConnection[] connections ;
  {
  connections=new CConnection[MaxConSize];
  }


  public CConnection GetConnection(){
   for(int i=0;i<connections.length;i++){
    if(1==connections[i].status){
     continue;
    }
    else if(0==connections[i].status){
     connections[i].status=1;
     connections[i].pos=i;
     return connections[i];
    }
   }

   System.out.println("No connection available,Please wait");
   return null;
  }


  public void CloseConnection (CConnection con){

      if(-1==con.pos||0==con.pos){
          System.out.println("No such connection");
      }
      else
          connections[con.pos].status=0;
  }

  public void execute(String sql){

       System.out.println(sql);
      }
}



 public static class CConnection  {
  private int status=0;
  private int pos=-1;


 }

 }






Exception in thread "main" java.lang.NullPointerException
    at hello.C$CConnection.access$0(C.java:55)
    at hello.C$CConnectionManager.GetConnection(C.java:22)
    at hello.C.main(C.java:8)

You're declaring an array of 10 CConnection ( connections=new CConnection[MaxConSize]; ) but the elements in the array are actually null. 您正在声明一个由10个CConnection的数组( connections=new CConnection[MaxConSize]; ),但该数组中的元素实际上为空。

So when doing : if(1==connections[i].status) it throws a NPE 因此,在执行以下操作时: if(1==connections[i].status)会引发NPE

To fix it, instantiate your CConnection objects in the constructor : 要解决此问题,请在构造函数中实例化CConnection对象:

private CConnection[] connections;

public CConnectionManager (){
   connections=new CConnection[MaxConSize];
   for(int i = 0; i < connections.length; i++){
        connections[i] = new CConnection();
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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