我试图编写一个if条件来检查包含许多对象的列表中是否存在一个值,这是我的代码:
List<TeacherInfo> teacherInfo=ServiceManager.getHelperService(TeacherManagementHelper.class, request, response).getTeacherInfoId();
if(teacherInfo.contains(inputParam))
{
out2.println("<font color=red>");
out2.println("Id Not Available");
out2.println("</font>");
}
else
{
out2.println("<font color=green>");
out2.println("Id Available");
out2.println("</font>");
}
Run Code Online (Sandbox Code Playgroud)
执行第一句后getTeacherInfoId()方法成功返回一个对象列表,在那些对象中我要检查任何对象的值是否相同inputParam.我上面的代码是对的吗?如果有错,请帮助我.
Jof*_*rey 26
contains(Object o)内部基于equals列表对象和输入之间,如文档所述.
既然你说这inputParam是一个整数,那么代码的当前状态就无法工作,因为你将一个整数与TeacherInfo对象进行比较,所以它们永远不会相等.我相信你想要比较inputParam一个特定的TeacherInfo对象领域.
如果您使用的是Java 8,则可以使用流API而不是contains():
List<TeacherInfo> teacherInfo=ServiceManager.getHelperService(TeacherManagementHelper.class, request, response).getTeacherInfoId();
if (teacherInfo.stream().anyMatch(ti -> ti.getId() == inputParam)) {
// contains the id
} else {
// does not contain the id
}
Run Code Online (Sandbox Code Playgroud)
对于以前的java版本,替代方法contains()是迭代列表并手动将整数与TeacherInfo字段进行比较:
private static boolean containsTeacherId(List<TeacherInfo> teacherInfos, int id) {
for (TeacherInfo ti : teacherInfos) {
if (ti.getId() == inputParam) { // I used getId(), replace that by the accessor you actually need
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
然后:
List<TeacherInfo> teacherInfo=ServiceManager.getHelperService(TeacherManagementHelper.class, request, response).getTeacherInfoId();
if (containsTeacherId(teacherInfo, inputParam)) {
// contains the id
} else {
// does not contain the id
}
Run Code Online (Sandbox Code Playgroud)
注意:如果您不需要除ID本身之外的其他信息,我建议从所调用的方法返回ID列表getTeacherIds(),特别是如果此信息来自数据库.