以下 for 循环 ( for (int curr = 0; curr<working.size(); curr++){
) 循环应运行 n 次,其中 n 是称为工作的 ArrayList 的大小。然而,即使在验证 ArrayList 中有多个元素之后,循环也只运行一次。为什么是这样?
String sql = "SELECT time FROM `tutors`.`appointments`"
+ "WHERE tutorID = ? AND date = ?";
try{
for (int curr = 0; curr<working.size(); curr++){
System.out.println("working size: " + working.size());
System.out.println("running for the time: " + curr);
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, working.get(curr).getTutorID());
ps.setDate(2, toReturn);
ResultSet rs = ps.executeQuery();
while(rs.next()){
Time t = rs.getTime("time");
System.out.println("RS HAS : " + t);
long beforeLong = t.getTime()-900000;
long afterLong = t.getTime()+900000;
Time beforeTime = new Time(beforeLong);
Time afterTime = new Time(afterLong);
if (!time.before(beforeTime) && !time.after(afterTime)){
System.out.println("removed" + working.get(curr).getName());
working.remove(curr);
}
}
}
} catch(SQLException e) {e.printStackTrace();}
PS - 无论我将 try/catch 放在 for 循环内部还是外部,我都会遇到同样的问题。
最佳答案
迭代时删除元素。
假设您的列表大小为 2 :在第一次迭代时,您删除一个元素,然后循环停止,因为 curr
是 1
,这是列表的大小。
如果删除元素,请使用迭代器迭代列表:
Iterator it = working.iterator();
while (it.hasNext()) {
...
it.remove();
}
ArrayList
迭代器对于此操作是安全的。
关于java - 为什么这个循环只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15447239/