4 回答

TA貢獻1856條經驗 獲得超17個贊
您需要 aList<String>
而不是單個String
,Arrays.asList(T...)
可能是最簡單的解決方案:
Patient?patientobj?=?new?Patient("sean",?"john",?Arrays.asList("allergy1"));
如果你有更多的過敏癥
Patient?patientobj?=?new?Patient("sean",?"john",? ????????Arrays.asList("allergy1",?"allergy2"));

TA貢獻2003條經驗 獲得超2個贊
public class Patient {
private String patientfirstName;
private String patientLastName;
private List<String> allergyList;
public Patient(String patientfirstName, String patientLastName,
List<String> allergyList) {
this.patientfirstName = patientfirstName;
this.patientLastName = patientLastName;
this.allergyList = allergyList;
}
*Patient patientobj = new Patient("sean","john","allegry1");*// this is wrong you have to pass a list not the string. you should do something like this:
// first create a list and add the value to it
List<String> list = new ArrayList<>();
list.add("allergy1");
// now create a object and pass the list along with other variables
Patient patientobj = new Patient("sean","john",list);

TA貢獻1802條經驗 獲得超4個贊
在我看來,你可以使用Varargs。感謝 varargs,您可以在參數中放入您想要的參數數量
public class Patient {
public String patientfirstName;
public String patientLastName;
public List<String> allergyList;
public Patient(String fName,String lName,String...aList) {
this.patientfirstName = fName;
this.patientLastName = lName;
this.allergyList = Arrays.asList(aList);
}
public static void main(String[] args) {
Patient firstPatient = new Patient("Foo", "Bar", "First Allergy","Second Allergy");
Patient secondPatient = new Patient("Foo", "Baz", "First Allergy","Second Allergy","Third Allergy","Fourth Allergy");
Patient ThirdPatient = new Patient("Foo", "Foo", "First Allergy");
}
參數“aList”就像一個數組,因為varargs就像一個沒有特定長度的數組,你在輸入參數時選擇的長度,如你所見
allergyList 的類型是可以選擇的。您也可以這樣做:
在“患者”屬性中:
public String[] allergyList;
在構造函數中:
public Patient(String fName,String lName,String...aList) {
this.patientfirstName = fName;
this.patientLastName = lName;
this.allergyList = allergyList;
}

TA貢獻1818條經驗 獲得超3個贊
您還有一種解決方案,只需添加該類的一個構造函數即可Patient。
public Patient (String patientfirstName,String patientLastName,String allergeyList){
this.patientfirstName = patientfirstName;
this.patientLastName = patientLastName;\
this.allergeyList = new ArrayList<>( Arrays.asList(allergeyList));
}
添加回答
舉報