简体   繁体   中英

How do i convert this for each into a for loop?

I am unable to change this foreach into a for loop. I can't use a foreach while using linked lists so i need to change this into a for loop instead

 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;
}*/

What about this?

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;
}

By the way, it is always better to use for-each style loop, since it provides more readability and convenience

EDIT : Since you mentioned linked list, it is better to use linked list iterator to iterate over your collection.

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;
}

You can also use while loop for that

while (iter.hasNext()) {
// do the work
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM