在 Java 中停止 ArrayList 的迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6292457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:14:09  来源:igfitidea点击:

Stopping an iteration of an ArrayList in Java

javaarraylistiteration

提问by Peter

I'm iterating an ArrayListof clients named clientListthat contains clients from the class Client (user,pass)

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

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

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

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

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

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)但如果在 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;
                    }
                }
            }
        }

回答by Kaj

You should breakout of the loop when the value is found.

break当找到该值时,您应该退出循环。

for (something) {
   if (anotherThingIsFound) {
      break;
   }
}
//Execution will continue here when you break...

Note, that it also is possible to break out of nested loops, with help of labels. E.g.

请注意,在标签的帮助下,也可以打破嵌套循环。例如

outer:
while (someCondition) {
   for (criteria) {
      if (somethingHappened) {
         break outer; 
      }
      if (anotherThingHashHappened) {
         break;
      }
   }
   //Execution will continue here if we execute the "normal" break.
}
//Execution will continue here when we execute "break outer;"

continuedoes also work with labels.

continue也适用于标签。

回答by Jon Skeet

Why not just break?

为什么不只是break

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

(I'm assuming you need to tell the difference between getting to the end and findingsomeone and getting to the end and notfinding someone. You probably only need one variable though, rather than two...)

(我假设您需要区分到达终点与找到某人以及到达终点与找到某人之间的区别。不过,您可能只需要一个变量,而不是两个……)

With your whileloop attempt, you're going to iterate over the whole list forever if the user isn't found, and even if the user isfound, it will loop over the whole list once - because your for loop is insidethe while loop. The while condition is only checked once per iteration of the while loop.

有了您的while循环尝试,你会遍历整个列表永远如果用户没有找到,并且即使用户发现,它会遍历整个列表一次-因为你的for循环是while循环. while 循环的每次迭代仅检查一次 while 条件。

回答by MGwynne

You need to use the breakkeyword:

您需要使用break关键字:

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

See Java break keyword documentation.

请参阅Java break 关键字文档

回答by Buhake Sindi

if you want to use your foundattribute, introduce a breakand remove while loop:

如果您想使用您的found属性,请引入一个break并删除 while 循环:

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

    if (found)
        break;
}

That way, you don't need to use the whileloop:

这样,您就不需要使用while循环:

回答by Marcin Michalski

Skipped null safety and class cast safety for simplicity

为简单起见,跳过了空安全和类转换安全

public class Cliente {
    public boolean equals(Object other){
         Cliente cOther = (Cliente) other;
         return this.getUser().equals(other.getUser()) &&
                this.getPassword().equals(other.getPassword())
    }
    public int hashCode(){
        return this.getUser().hashCode()*this.getPassword().hashCode();
    }
}

...
Cliente c = new Cliente();
c.setPassword(pass);
c.setUser(user);
boolean found = clientList.contains(c);

回答by Anon

Using breakworks fine, but if you wanted to do it with a while loop instead then you could do it like this:

使用break工作正常,但如果你想用 while 循环来代替,那么你可以这样做:

    Iterator<Client> it = clientList.iterator();
    while (it.hasNext() && !found) {
        Client c = it.next();
        userA = c.getUser();
        if (userA.equals(user)) {
            passA = c.getPassword();
            if (passA.equals(pass)) {
                loginOK = true;
                found = true;
            }
        }
    }

回答by duffymo

I'd write it this way:

我会这样写:

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

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

我的猜测是你没有在你的Cliente班级中覆盖 equals 和 hashCode或者它不正确。