title: Assigning null to ArrayList items in Java
body: <p>I have the following code:</p>
  
  <pre><code>static ArrayList&lt;PreparedStatement&gt; alPrepStmts = new ArrayList&lt;PreparedStatement&gt;();
  
  static PreparedStatement m_stmtOne;
  static PreparedStatement m_stmtTwo;
  static PreparedStatement m_stmtThree;
  ...
  static PreparedStatement m_stmtOneHundred;
  
  private static void init() {
      alPrepStmts.add(m_stmtOne);
      alPrepStmts.add(m_stmtTwo);
      alPrepStmts.add(m_stmtThree);
      ...
      alPrepStmts.add(m_stmtOneHundred);
  }
  
  private static void work() {
      if(m_stmtOne == null) {
          // assign m_stmtOne
      }
      // use m_stmtOne
  }
  
  private static void close() throws SQLException {
      for(PreparedStatement ps : alPrepStmts) {
          if(ps != null) {
              ps.close();
              ps = null;
          }
      }
  }
  </code></pre>
  
  <p>init() gets called once. work() and close() may get called several times. The problem is that after calling close(), the PreparedStatements are not set to null. The next time I call work(), m_stmtOne is not null, but is closed. I supposed I can check if m_stmtOne is open, but I am wondering how can I assign null to the members of the container.</p>
  
  <p>I also tried using iterators and it does not work either. The if conditional below is never true.</p>
  
  <pre><code>private static void ClosePreparedStatements() throws SQLException {
      for(Iterator&lt;PreparedStatement&gt; it = alPrepStmts.iterator(); it.hasNext();) {
          PreparedStatement ps = (PreparedStatement)it.next();
          if(ps != null) {
              ps.close();
              ps = null;
          }
      }
  }
  </code></pre>
  
  <p>I know I can close and assign every statement manually, but I'm just wondering what is the best way to assign null to elements in a container.</p>