首页 > 解决方案 > 使用 for-each 循环时可以跳过部分数组吗?

问题描述

我被告知只从数组中返回具有给定长度的字符串。我可以通过常规的 for 循环轻松做到这一点。但我最近发现了 for-each 循环,我正在尝试学习如何使用它们。这个问题似乎可行,但我可能错了。

有我正在处理的代码:

public List wordsWithoutList(String[] words, int len) {
    String[] temp = new String[0];
    for (String i : words) {
        if (i.length() != len) {
            temp = new String[temp.length + 1];
            temp[i] = words[i];
        }
    }
    return temp;
}

标签: javaloopsforeach

解决方案


要从数组中返回给定长度的字符串,您可以使用简单的if语句:

public List<String> givenLength(String[] words, int len) {
    List<String> strings = new ArrayList<>();
    for (String word : words) {
        if (word.length() == len) {
            strings.add(word);
        }
    }
    return strings;
}

推荐阅读