break不会停止for循环

时间:2018-01-05 11:12:33

标签: java android foreach

我的代码存在问题,我希望在Firebase中找到匹配项,删除项目并停止查找匹配项,但事实并非如此,会发生什么情况,它会删除所有元素

for(DataSnapshot dataSnapshot2: dataSnapshot.getChildren()) {
    Product product = dataSnapshot2.getValue(Product.class);
    String product_name = producto.getNombre();
    String key = dataSnapshot2.getKey();

    if(spinner_product.getSelectedItem().toString().equals(product_name)) {
        bbdd.child(key).removeValue();
        break;
    }
}

2 个答案:

答案 0 :(得分:0)

编辑:正如@Rafal所说,在循环外设置布尔值显然更好!

永远不要使用"old-url", "new-url" "/product/0903-HUGGIEGK/Dangle-Hoop-Earrings-for-Girls-with-CZ-and-Heart-Dangle-in-14K-Gold/", "/product/dangle-hoop-earrings-for-girls-with-cz-and-heart-dangle-in-14k-gold/" "/product/0954-HUGGIEGK/Dangle-Hoop-Earrings-for-Girls-with-CZ-and-Butterfly-Dangle-in-14K-Gold/", "/product/dangle-hoop-earrings-for-girls-with-cz-and-butterfly-dangle-in-14k-gold/" "/product/10049Y4JBT/Petite-Lever-Back-Earrings-for-Little-Girls-in-14K-Yellow-Gold-with-Blue-Topaz---High-End-Childrens-Earrings/", "/product/petite-lever-back-earrings-for-little-girls-in-14k-yellow-gold-with-blue-topaz-high-end-childrens-earrings/" ,因为它非常不稳定。

即使break循环更好,您也可以试试这个:

Instanciate boolean:

do{}while();

答案 1 :(得分:0)

就像@Lozenzo的答案一样,但在循环中声明一个标志并不是最好的解决方案,并注意到循环不会停止,直到它检查dataSnapshot.getChildren()中的所有元素!

尝试在循环之前声明标志并将其添加到循环条件。您可能会发现while循环类型对此任务很有用。