0

这是一个连接池的例子。我想我已经初始化了所有对象,但是我得到了空指针异常。我该如何解决这个问题?

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)
4

1 回答 1

3

您声明了一个 10 CConnection( connections=new CConnection[MaxConSize];) 的数组,但数组中的元素实际上为空。

所以在做的时候:if(1==connections[i].status)它会抛出一个NPE

要修复它,请CConnection在构造函数中实例化您的对象:

private CConnection[] connections;

public CConnectionManager (){
   connections=new CConnection[MaxConSize];
   for(int i = 0; i < connections.length; i++){
        connections[i] = new CConnection();
   }
}
于 2013-11-02T11:13:00.140 回答