我无法将此foreach更改为for循环。我不能在使用链接列表时使用foreach,因此我需要将其更改为for循环
private boolean login(String username, String password) {
MyList<Admin> admins = null;
XStream xstream = new XStream(new DomDriver());
try {
ObjectInputStream is = xstream.createObjectInputStream(new FileReader("Admins.xml"));
admins = (MyList<Admin>) is.readObject();
is.close();
}
catch(FileNotFoundException e) {
admins = new MyList<Admin>();
txtFeedBackArea.setText("Password File not located");
return false;
}
catch (Exception e) {
txtFeedBackArea.setText("Error accessing Password File");
return false;
}
for (Admin admin: admins) {
if(admin.getUsername().equals(username) &&
admin.getPassword().equals(password))
return true;
}
return false;
}*/
那这个呢?
for (int i = 0; i < admins.size(); i++) {
final Admin a = admins.get(i);
if(a.getUsername().equals(username) && a.getPassword().equals(password))
return true;
}
顺便说一句,最好使用for-each样式循环,因为它提供了更多的可读性和便利性
编辑:既然您提到了链表,最好使用链表迭代器遍历集合。
for (ListIterator<Admin> iter = admins.listIterator(0); iter.hasNext()) {
final Admin a = iter.next();
if(a.getUsername().equals(username) && a.getPassword().equals(password))
return true;
}
您也可以使用while循环
while (iter.hasNext()) {
// do the work
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句