在 Java 中停止 ArrayList 的迭代 [英] Stopping an iteration of an ArrayList in Java

查看:24
本文介绍了在 Java 中停止 ArrayList 的迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在迭代一个名为 clientList 的客户端的 ArrayList,其中包含来自 Client (user,pass)

I'm iterating an ArrayList of clients named clientList that contains clients from the class Client (user,pass)

ArrayList<Client> clientList= new ArrayList<Client>();

这是迭代.如果找到给定的用户(user)并且密码(pass)匹配,我想停止迭代:

Here's the iteration. I want to stop the iteration if it founds a given user (user) and if the password (pass) matches:

            for (Client c : clientList) {
                userA = c.getUser();
                if (userA.equals(user)) {
                    passA = c.getPassword();
                    if (passA.equals(pass)) {
                        loginOK = true;
                        found= true;
                    }

我正在尝试以下 while (found == false),但如果在 ArrayList 上找不到用户,它就会卡住:

I was trying the following while (found == false) but it's get stucked if it doesnt find an user on the ArrayList:

        while (found == false) { /
            for (Client c : clientList) {
                userA = c.getUser();
                if (userA.equals(user)) {
                    passA = c.getPassword();
                    if (passA.equals(pass)) {
                        loginOK = true;
                        found= true;
                    }
                }
            }
        }

推荐答案

我会这样写:

while (!found) { 
    for (Cliente c : clientList) {
        userA = c.getUser();
        if (userA.equals(user)) {
            passA = c.getPassword();
            if (passA.equals(pass)) {
                loginOK = true;
                found= true;
                break;
            }
        }
    }
}

我的猜测是您没有在 Cliente 类中覆盖 equals 和 hashCode 或者它不正确.

My guess is that you didn't override equals and hashCode in your Cliente class or it's not correct.

这篇关于在 Java 中停止 ArrayList 的迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆