I have the following code:
static ArrayList<PreparedStatement> alPrepStmts = new ArrayList<PreparedStatement>();
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;
}
}
}
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.
I also tried using iterators and it does not work either. The if conditional below is never true.
private static void ClosePreparedStatements() throws SQLException {
for(Iterator<PreparedStatement> it = alPrepStmts.iterator(); it.hasNext();) {
PreparedStatement ps = (PreparedStatement)it.next();
if(ps != null) {
ps.close();
ps = null;
}
}
}
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.
Your assignment
ps = nullassigns only the local variable, it does not modify the original container. You should use theremovemethod ofjava.util.Iterator(in your second code snipped instead ofps = null) to remove an element from the container. Note this removes the element from the container, not replace it with null in the container.Even if you remove the element from the container, it will not change the value of, e.g.
m_stmtOne, which it sounds like you want to have happen also. You will have to do that some other way.It also seems
init()just adds 100 nulls to your list of prepared statements. Assigning a non-null value tom_stmtOnelater will not change the list. In other words,m_stmtOnegets added to the list by value, not by reference.