当我输入许多日期元素时遇到麻烦,所有其他元素都成为我输入的最后日期。
超类:
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);
}
子类:
for(i=0; i<emp.emNum(); i++){
System.out.println("Name: "+ emp.printName(i) + " Date Joined: " + emp.printCal(i));
}
输出
例如,2个元素输入):
Name: John, Date Joined: December 25, 2000
Name: Peter, Date Joined: December 25, 2000
答案 0 :(得分:1)
每次要添加GregorianCalendar
时,都需要创建一个public void addDate(int month, int day, int year){
date.add(new GregorianCalendar(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
}
实例。
在java中向List添加内容时,基本上只添加对Object的引用。如果使用get(i)修改它,则将修改Object
{{1}}
答案 1 :(得分:0)
您正在重用对象startDate,这是您的问题。您需要为每条新记录创建一个新的GregorianCalendar实例。
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);
}