Fddw
Fddw

Reputation: 11

How to remove an element from array of objects?

public class Patient extends Person {
    private String Diagnosis;
    private Appointment[] appointment = new Appointment[2];
    private int numberofAppointment;
    public static int numberOfPatient;

    public void DellappointmentAT(int index) {
        appointment[index].setAvailable(true);
        numberofAppointment--;
    }
}

The class i created, has an Array of object as data fields and i have this method that should remove an element from this array, I want to delete the element without changing the array size.

Upvotes: 1

Views: 71

Answers (2)

Maurice Perry
Maurice Perry

Reputation: 9650

How about this:

public void DellappointmentAT(int index) {
    appointment[index].setAvailable(true);
    numberofAppointment--;
    for (int i = index; i < numberofAppointment; ++i) {
        appointment[i] = appointment[i+1];
    }
}

Upvotes: 0

Anthonius
Anthonius

Reputation: 340

Removing an element will impact the array size.

If you really need the initial array to stay the same, there are 2 common approaches:

  1. Create another array so your initial array is not modified
  2. Soft delete - create a remove flag inside the object. That way, you can differentiate between removed data and the array size stays the same

Upvotes: 1

Related Questions