我想用HashMap的(Appointment)填充ArrayList(Appointment_List),但是每次我需要更改指定元素的值(Appt_Start_Time和endtime)时。
这是代码:
for (int i = 1; i < Appt_Length; i++) {
Start_Time = End_Time;
Start_Minute = Curr_Start_Minute;
Start_Minute += My_Calendar.Get_Time_Interval();
if (Start_Minute >= 60) {
Tmp_Start_Hour += 1;
Curr_Start_Minute = 0;
} else {
Curr_Start_Minute = Start_Minute;
}
End_Time = Time.Get_Index_Time(Tmp_Start_Hour, Curr_Start_Minute);
Appointment.remove("Appt_Start_Time");
Appointment.put("Appt_Start_Time", Start_Time);
Appointment.remove("endtime");
Appointment.put("endtime", End_Time);
Appointment_List.add(Appointment);
}
但是,在执行此代码后,我在Appointment_List中获得了约会,但所有约会的
Appointment.get("Appt_Start_Time")
和Appointment.get("endtime")
等于循环所附带的最后一个值。为什么在添加新元素时每次都要重置Appt_Start_Time和结束时间?
最佳答案
约会是每次迭代都相同的HashMap实例。您应该这样做:Appointment = new HashMap();
// ... do something with appointment ...
Appointment_List.add(Appointment)
这样,您将在每次迭代中将一个新的新映射放入列表。
关于java - 用哈希图填充ArrayList,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3413555/