开发者

Fill ArrayList with hashmaps

I want to fill an ArrayList (Appointment_List) with Has开发者_JS百科hMap's (Appointment), but each time I need to change the value of specified elements(Appt_Start_Time and endtime).

Here is the code:

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);
}

But after I execute this code I got the appointments in the Appointment_List but all of them have Appointment.get("Appt_Start_Time") and Appointment.get("endtime") equals to last values the loop come with.

Why is Appt_Start_Time and endtime reseted each time, when I add a new element?


Appointment is THE SAME HashMap instance every iteration. You should do something like that:

Appointment = new HashMap();

// ... do something with appointment ...

Appointment_List.add(Appointment)

This way you'll put a fresh new map to the list each iteration.


Your objects hold a reference to the Start_Time. Since you keep reusing the same variable, only thing that changes is the pointer to the object. That way, all your objects have a field that points to the same object.

Try using a new implementation of a Date for each iteration of the loop.


You need to create a new instance of Start_Time and End_Time in the for loop. If you don't, the same object gets added every single time, thus also pointing to the same data in your memory.


Use clone() when adding a new object to the map.

When adding an object to a map, the added object is only referenced by the map.


I think the code should look more like this:

public class Appointment {
    public Appointment(Date startTime, Date endTime) {
    }
}

public void fillAppointments() {
    int totalAppointments = 10;
    List<Appointment> appointments = new ArrayList<Appointment>();
    Date startTime = new Date();
    Date endTime = new Date();
    for (int i = 1; i < totalAppointments; i++) {
        startTime = new Date(endTime.getTime());
        // ... other magic code ...
        endTime = new Date();
        appointments.add(new Appointment(startTime, endTime));
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜