在此示例代码中,我从数据库获取两条记录,然后将这些数据设置为放入 ArrayList
的 smsDTO
对象。如果我在另一个类中迭代这个 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());
}
}
最佳答案
public ArrayList<SmsDTO> getReulst() {
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
ArrayList<SmsDTO> ar = new ArrayList<SmsDTO>();
SmsDTO sms = null;
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()) {
sms = new SmsDTO();
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;
}
}
关于java - 列表中的用户定义对象未正确迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38609528/