简体   繁体   中英

Adding a date element in GregorianCalendar ArrayList Java

I'm having trouble when I input many date elements, all the other elements become the last date I input.

SuperClass:

SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
String year = "1995", month = "12", day = "24";
GregorianCalendar startDate = new GregorianCalendar(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));

public void addDate(int month, int day, int year){
    date.add(startDate);
    startDate.set(GregorianCalendar.DAY_OF_MONTH, day);
    startDate.set(GregorianCalendar.YEAR, year);
    startDate.set(GregorianCalendar.MONTH, month);
}
public String printCal(int i){
    return sdf.format(date.get(i).getTime());
}
public void addName(String newName){
    name.add(newName);
}

Sub-Class:

for(i=0; i<emp.emNum(); i++){
                System.out.println("Name: "+ emp.printName(i) + " Date Joined: " + emp.printCal(i));
            }

Output

For example, 2 element inputs):

Name: John, Date Joined: December 25, 2000

Name: Peter, Date Joined: December 25, 2000

You need to create an instance of GregorianCalendar each time you wish to add it. In java when you add something to a List you basically only add a reference to an Object. If you modify it using get(i), you will modify the Object

public void addDate(int month, int day, int year){
    date.add(new GregorianCalendar(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
}

You are reusing the object startDate and this is your problem. You need to create a new instance of GregorianCalendar for each new record.

public void addDate(int month, int day, int year)
{
    GregorianCalendar myDate = new GregorianCalendar();
    myDate.set(GregorianCalendar.DAY_OF_MONTH, day);
    startDate.set(GregorianCalendar.YEAR, year);
    startDate.set(GregorianCalendar.MONTH, month);
    date.add(startDate);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM