我试图将参数传递给构造函数但是我被困在方法中用于arraylist的内容。 构造:
public Company(int companyid,String companyname, String companyowner, String startdate, String description,
ArrayList<String> departments) {
this.companyid=companyid;
this.companyname = companyname;
this.companyowner = companyowner;
this.startdate = startdate;
this.description = description;
this.departments = departments;
}
在方法中调用参数:
Company company = new Company(obj.getInt("companyID"),obj.getString("comapnyName"),obj.getString("companyOwner"),obj.getString("companyStartDate"),obj.getString("companyDescription"),obj.getString("companyDepartments"));
company.setCompanyid(obj.getInt("companyID"));
company.setCompanyname(obj.getString("comapnyName"));
company.setCompanyowner(obj.getString("companyOwner"));
company.setStartdate(obj.getString("companyStartDate"));
company.setDescription(obj.getString("companyDescription"));
// Genre is json array
JSONArray companydept = obj.getJSONArray("companyDepartments");
ArrayList<String> departments = new ArrayList<String>();
for (int j = 0; j < companydept.length(); j++) {
departments.add((String) companydept.get(j));
}
company.setDepartments(departments);
我很困惑在方法中使用什么。预期的参数是Arraylist但是方法中使用的实际参数是String我不知道在那里使用什么。
答案 0 :(得分:0)
你很亲密。
在公司的构造函数之前移动以下代码(在您调用新公司之前)。
JSONArray companydept = obj.getJSONArray("companyDepartments");
ArrayList<String> departments = new ArrayList<String>();
for (int j = 0; j < companydept.length(); j++) {
departments.add((String) companydept.get(j));
}
并致电:
Company company = new Company(obj.getInt("companyID"),obj.getString("comapnyName"),obj.getString("companyOwner"),obj.getString("companyStartDate"),obj.getString("companyDescription"),obj.getString("companyDepartments"), departments);
答案 1 :(得分:0)
您有几个选择:
1)您可以从ArrayList<String> departments
构造函数中删除Company
参数,并像现在一样拥有company.setDepartments(departments);
setter。
2)首先创建ArrayList<String> departments
,然后将其传递给构造函数:
// Genre is json array
JSONArray companydept = obj.getJSONArray("companyDepartments");
ArrayList<String> departments = new ArrayList<String>();
for (int j = 0; j < companydept.length(); j++) {
departments.add((String) companydept.get(j));
}
Company company = new Company(obj.getInt("companyID"),
obj.getString("comapnyName"),
obj.getString("companyOwner"),
obj.getString("companyStartDate"),
obj.getString("companyDescription"),
departments); // <--- Pass the ArrayList here
3)让公司构造函数通过传递ArrayList
来构建JSONArray
。
public Company(int companyid,String companyname,
String companyowner, String startdate,
String description, JSONArray companydept) {
this.companyid=companyid;
this.companyname = companyname;
this.companyowner = companyowner;
this.startdate = startdate;
this.description = description;
// build it in the constructor here:
this.departments = new ArrayList<String>();
for (int j = 0; j < companydept.length(); j++) {
departments.add((String) companydept.get(j));
}
}