在這個示例代碼中,我從數據庫中獲取兩條記錄,然後我已將該數據設置爲smsDTO
對象,我已將其放入ArrayList
。如果我重複這個ArrayList
在另一個類,最後一次記錄打印兩次而不是第一個記錄。用戶定義的對象裏面的列表不能正確迭代
數據庫類
public ArrayList<SmsDTO> getReulst() {
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
ArrayList<SmsDTO> ar=new ArrayList<SmsDTO>() ;
SmsDTO sms = new SmsDTO();
try {
conn = getConnection();
String query = "select pt.P_MOBILE,st.S_FIRSTNAME,st.REF_ID from parent_info pt join student_info st on pt.REF_ID = st.REF_ID where st.S_CLASS_TO_JOIN = 10;";
pstmt = conn.prepareStatement(query); // create a statement
rs = pstmt.executeQuery();
// extract data from the ResultSet
while (rs.next()) {
long phone = rs.getLong(1);
sms.setPhone(phone);
String student_name = rs.getString(2);
sms.setStudentname(student_name);
String ref = rs.getString(3);
sms.setRef(ref);
ar.add(sms);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return ar;
}
}
另一類
method()
{
ArrayList<SmsDTO> lhst = null;
try {
lhst = db.getReulst();
for (Iterator iterator = lhst.iterator(); iterator.hasNext();) {
SmsDTO smsDTO = (SmsDTO) iterator.next();
System.out.println(smsDTO.getStudentname());
}
}
這並不是說它的循環錯了,你只需重複添加一個'SmsDTO'實例('s''永遠不會被重新分配)並修改這個實例。所以你在'List'中留下了'x'次'SmsDTO'的相同實例,其中這個實例具有最後迭代的數據庫行的數據。 – SomeJavaGuy
你是對的 –