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));
}
添加回答
举报