我知道StackOver流程不是您可以发布作业并让人们为您完成的地方 但我在我的智慧结束时我尝试了简单的调试方法,比如打印线,我可以看到结果,只是一些arraylist如何在我添加时保存项目
我们只想说数组添加两个项目
first item(name1,job1,event1,date1,location1)
second item(name2,job2,event2,date2,location2)
name1 test234
name2 test234
name2 outloop
name2 outloop
public class Homework {
// ...
private int cin;
private String[] jobarray;
private String[] eventarray;
private Timetable tb;
private String[] namesarray;
//...
public ArrayList retrievebyname(String name, String date) {
ResultSet rs = null;
DBController db = new DBController();
ArrayList<Timetable> list = new ArrayList();
// start of for loop**
for (int k = 0; k < cin; k++) {
// step 1 - establish connection to database
db.getConnection();
// step 2 - declare the SQL statement
String dbQuery = "select event.eventName,Timetable.location,Timetable.date "
+ "From Timetable " + "inner join event "
+ "on event.eventId=Timetable.eventId " + "inner join VolunteerJob "
+ "on VolunteerJob.ID= Timetable.jobId " + "Where JobName='"
+ jobarray[k] + "'" + "and Timetable.date ='" + date + "'"
+ "and eventName='" + eventarray[k] + "'";
// step 3 - to retrieve data using readRequest method
rs = db.readRequest(dbQuery);
try {
if (rs.next()) {
tb.setName(namesarray[k]);
tb.setJobName(jobarray[k]);
tb.setEventName(rs.getString("eventName"));
tb.setDate(rs.getString("date"));
tb.setLocation(rs.getString("location"));
// **Adding the item retrieve into ArrayList called List**
list.add(k, tb);
System.out.println(list.get(k).getName() + " test234");
}
} catch (Exception e) {
e.printStackTrace(); // fail to retrieve, print error message
}
// step 4 - close connection
db.terminate();
} // end of for loop**
System.out.println(list.get(0).getName() + " outloop");
System.out.println(list.get(1).getName() + " outloop");
return list;
}
}
答案 0 :(得分:3)
编辑完成后,我发现您在方法开头创建了一个Timetable
实例。这还不够。
这意味着您反复将相同的对象添加到列表中,并且在每次迭代中都会覆盖其属性。
您必须为添加到列表中的每个对象创建Timetable
的新实例。
tb = new Timetable ();
tb.setName(namesarray[k]);
tb.setJobName(jobarray[k]);
tb.setEventName(rs.getString("eventName"));
tb.setDate(rs.getString("date"));
tb.setLocation(rs.getString("location"));
list.add(k, tb)