Java Arraylist/List 错误

1 java netbeans exception arraylist

我已经标记了给我带来麻烦的那条线

private void EditButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
Run Code Online (Sandbox Code Playgroud)

DefaultListModel PatientListModel = new DefaultListModel();

for (Patient s : PatientList) {
    int AccNum = Integer.parseInt(IDTextField.getText());

    if (AccNum == s.getAccountNumber()) {

        s.setName(NameTextField.getText());
        s.setAge(Integer.parseInt(AgeTextField.getText()));
        s.setAddress(AddressTextField.getText());
        String PatientSex = "";

        if (MaleRadioButton.isSelected()) {
            PatientSex = "Male";
        }

        if (FemaleRadioButton.isSelected()) {
            PatientSex = "Female";
        }

        s.setSex(PatientSex);
        s.setPhone(PhoneTextField.getText());
        ArrayList<PatientCondition> PatientConditions3 = new ArrayList();
  ===>      PatientConditions3 = (ArrayList<PatientCondition>) ConditionsJList.getSelectedValuesList(); //error here
        s.setConditionsList(PatientConditions3);
        PatientInfoLabel2.setText("Patient Details Updated");

        for (Patient f : PatientList) {
            PatientListModel.addElement(f.getAccountNumber() + "-" + f.getName());
        }

        PatientJList.setModel(PatientListModel);
        UpdateAllViews();

        //       
    }
}
}                                 
Run Code Online (Sandbox Code Playgroud)

错误是:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.util.Collections$EmptyList cannot be cast to java.util.ArrayList
Run Code Online (Sandbox Code Playgroud)

Kep*_*pil 5

我认为错误消息非常有用。你不能做那个演员。

你应该重新定义你PatientConditions3的类型List<PatientCondition>。针对接口List而不是特定实现(如ArrayList. 此外,您应该重命名它以遵循 Java 命名约定:

List<PatientCondition> patientConditions3;
Run Code Online (Sandbox Code Playgroud)

如果您需要将接收到的转换List为例如 an ArrayList,您可以使用接收到的元素创建一个新的List

patientConditions3 = new ArrayList<PatientCondition>(ConditionsJList.getSelectedValuesList());
Run Code Online (Sandbox Code Playgroud)