Wayne Daly
Wayne Daly

Reputation: 55

Deleting from Array but keep order?

Ok so im trying to delete an object from my array, each object has a user id, so the 0 index in array would hold an object with id one. when I delete object wih id of 2 for example I want to delete the 1 index in array and redo the model and display that. so I want the model to show 1:blah then 3:Blah and so on leaving out the deleted ones

 private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {

// arrays index not working when deleted
int reply = JOptionPane.showConfirmDialog(null, "Are you sure?","Delete Patient: " +     
NameTextField.getText(), JOptionPane.YES_NO_OPTION);
    if (reply == JOptionPane.YES_OPTION) {

        int Num = Integer.parseInt(IDTextField.getText());
        int Num1 = Num--;


        for(Patient s: PatientList)
        {

            if(Num == s.getAccountNumber())
            {
                PatientList.remove(Num1);
                break;

            }
        }

        DefaultListModel PatientListModel = new DefaultListModel(); 

    for(Patient s: PatientList)
    {

   PatientListModel.addElement(s.getAccountNumber() + "-" + s.getName());  
 }
   PatientJList.setModel(PatientListModel); 

   //delete procedures for that id



      JOptionPane.showMessageDialog(null, "Patient: " + NameTextField.getText() + "     

 Deleted!");
      NameTextField.setText("");
    AgeTextField.setText("");
    AddressTextField.setText("");
    SexGroup.clearSelection();
    PhoneTextField.setText("");
    IDTextField.setText("");
     PatientJList.clearSelection();


    }
    else {


    }
}

Upvotes: 1

Views: 105

Answers (2)

Mukul Goel
Mukul Goel

Reputation: 8467

the Object you are talking about, maintain one more property in it called index. While adding this object to array, set the Object.index to the index of array.

Now do whatever you want to the array. But at the time of displaying array. Do like this

Object.index Object

Upvotes: 0

user2030471
user2030471

Reputation:

I believe instead of using the array index as the object id you should be maintaing this property in the object itself. Something like:

public class Patient {

    private int id;

    // getter and setter for id

    // rest of the class

}

Upvotes: 2

Related Questions