我有一个ArrayList,它包含以下class类型的元素:ListClass
public class ListClass {
String requestPath; //parse
List<String> paramsMandatory; //name, query
List<String> paramsOptional; //company
boolean needBody; //true
String mimeType; //String, json
public String getRequestPath() {
return requestPath;
}
public void setRequestPath(String requestPath) {
this.requestPath = requestPath;
}
public List<String> getParamsMandatory() {
return paramsMandatory;
}
public void setParamsMandatory(List<String> paramsMandatory) {
this.paramsMandatory = paramsMandatory;
}
public List<String> getParamsOptional() {
return paramsOptional;
}
public void setParamsOptional(List<String> paramsOptional) {
this.paramsOptional = paramsOptional;
}
public boolean isNeedBody() {
return needBody;
}
public void setNeedBody(boolean needBody) {
this.needBody = needBody;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
}
在另一个类中设置属性:PropSetter
public class PropSetter {
List<String> mp = new ArrayList<String>();
List<String> op = new ArrayList<String>();
public void setParameters() {
mp.add("force");
mp.add("name");
op.add("company");
op.add("location");
ListClass lc = new ListClass();
lc.setRequestPath("/parse");
lc.setParamsMandatory(mp);
lc.setParamsOptional(op);
lc.setNeedBody(false);
lc.setMimeType("String");
System.out.println("Set the props for ListClass");
}
}
我正试图以以下方式返回类型为ListClass
的ArrayList:
List<ListClass> cl = new ArrayList<ListClass>();
public void setCL() {
PropSetter ps = new PropSetter();
ps.setParameters();
ListClass lcl = new ListClass();
cl.add(lcl);
}
public List<ListClass> getPropList() {
return cl;
}
方法getPropList
返回类型为ListClass
的List。如何访问其中的元素?如果它是一个特定的数据类型,我可以使用Iterator或foreach循环。但这是一个类类型:ListClass
,我不知道如何访问元素,尤其是列表:paramsMandatory¶msOptional内部。
我试着显示以下元素:
CreateList cl = new CreateList();
cl.setCL();
List<ListClass> ll = cl.getPropList();
System.out.println("Size of Arraylist<ListClass>:" + ll.size());
for (ListClass l: ll) {
System.out.println("DS: " + l);
}
在我的主课堂上,我试着看看是否可以在里面打印一个参数,如下所示。
for (ListClass l: ll) {
System.out.println("DS: " + l.getRequestPath);
}
这给了我一个编译错误:getRequestPath cannot be resolved or is not a field
我试着打印数组的大小,它显示了正确的值:
System.out.println("Size of Arraylist<ListClass>:" + ll.size());
Size of Arraylist<ListClass>: 1
有人能告诉我如何访问来自getPropList
的元素吗
查看您得到的编译器错误,即:
getRequestPath cannot be resolved or is not a field
换句话说,编译器认为getRequestPath
是类ListClass
的成员,因为您忘记添加括号,以便向编译器指示getRequestPath
是一个方法。因此,您需要更改代码的行如下:
System.out.println("DS: " + l.getRequestPath());