gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:28:36 24 4
gpt4 key购买 nike

好吧,我试图从数组中删除一个对象,每个对象都有一个用户 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

}

关于java - 从数组中删除但保持顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15188547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com