Java 从数组中删除但保持顺序?

Java 从数组中删除但保持顺序?,java,Java,好的,我正试图从数组中删除一个对象,每个对象都有一个用户id,所以数组中的0索引将包含一个id为1的对象。例如,当我删除id为2的对象时,我想删除数组中的1索引,并重做模型并显示它。所以我希望模型显示1:blah,然后是3:blah,依此类推,去掉删除的部分 private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) { // arrays index not working when deleted in

好的,我正试图从数组中删除一个对象,每个对象都有一个用户id,所以数组中的0索引将包含一个id为1的对象。例如,当我删除id为2的对象时,我想删除数组中的1索引,并重做模型并显示它。所以我希望模型显示1:blah,然后是3:blah,依此类推,去掉删除的部分

 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 {


    }
}

我认为不应该使用数组索引作为对象
id
,而应该在对象本身中维护此属性。比如:

public class Patient {

    private int id;

    // getter and setter for id

    // rest of the class

}

您正在谈论的
对象
,在其中维护另一个名为
索引
的属性。将此对象添加到数组时,将
对象.index
设置为数组的索引

现在对数组执行任何操作。但在显示阵列时。你喜欢这样吗


Object.index对象

你的问题是?为什么不尊重Java命名约定呢?我在patient类中有这样的约定,当从patientlist中删除对象时,我会循环遍历它们,如果id num与您输入的要删除的num匹配,那么就去掉patientlist中的num-1。这有意义吗?在显示时,您可以调用
getId
,而不是在迭代列表时依赖数组索引。