删除方法帮助java

时间:2015-09-25 00:09:27

标签: java inheritance arraylist iterator

我目前正在开发一个项目,我创建了一个Appointment超类,包含Daily,Monthly和Yearly子类。我还创建了一个Calendar类,它具有一个ArrayList,其中包含作为日期的约会对象。在Calendar类中,我有一个add(),remove()和toString()方法。该 我需要建议的问题是remove()方法。在我的测试器类中,当我调用remove()来删除某个日期时,一旦找到日期,它就会删除ArrayList中的所有内容。我如何解决这个问题,以便只删除我想要的特定日期?

这是我的测试人员类:

/**
 * Demonstration of the Calendar and Appointment classes
 */
public class AppointmentDemo {
    public static void main(String[] args) 
    {
        Calendar calendar = new Calendar();

        calendar.add(new Daily(2000, 8, 13, "Brush your teeth."));
        calendar.add(new Monthly(2003, 5, 20, "Visit grandma."));
        calendar.add(new OneTime(2004, 11, 2, "Dentist appointment."));
        calendar.add(new OneTime(2004, 10, 31, "Trick or Treat."));
        calendar.add(new Monthly(2004, 11, 2, "Dentist appointment."));
        calendar.add(new OneTime(2004, 11, 2, "Dentist appointment."));


        System.out.println("Before removal of appointment: " + "\n" + calendar);
        calendar.remove(2004, 11, 2);
        //note that the daily appointment is removed because it occurs on
        //11/2/2004 (as well as many other days).  
        System.out.println("After removal of 11/2/2004 " + "\n" + calendar);
    }
}

这是我的remove()方法:

public class Calendar 
{
    private ArrayList<Appointment> calendar = new ArrayList<>(); 

    public void remove(int year, int month, int day)
    {   
        //iterate through ArrayList
        for(Iterator<Appointment> i = calendar.iterator(); i.hasNext();)
        {  
            Appointment date = i.next(); 
            if(date.occursOn(year, month, day))
            //if the element occurs on the input then remove that element
            {
                i.remove(); 
            }
        }
    }
}

我的结果:

 Before removal of appointment: 
 [2000/8/13: Brush your teeth., 
  2003/5/20: Visit grandma., 
  2004/11/2: Dentist appointment., 
  2004/10/31: Trick or Treat., 
  2004/11/2: Dentist appointment., 
  2004/11/2: Dentist appointment.]

 After removal of 11/2/2004 
 [2000/8/13: Brush your teeth., 
  2003/5/20: Visit grandma.]

0 个答案:

没有答案