使用增强的for循环搜索LinkedList

因此,我试图用增强的for循环替换for循环,但我无法使其正常工作,问题是它会进行搜索,当它找到要查找的名称时,它会返回inex -1。使用正常的for循环,它将返回正确的索引。 n是传递给方法的字符串,数组是链表

boolean found= false;
    for(O o: array) {
        if(o.getString().equals(n)) {
            System.out.println("\n"+n+ " is found at position " +array.indexOf(name)+"\n");
            found = true;
        }
    }

    for (int i = 0; i<array.size();i++) {
        if((array.get(i).getString()).equals(n)) {
            System.out.println("\n"+n+ " is found at position " +i+"\n");
            found = true;
        }
    }
melodylwx 回答:使用增强的for循环搜索LinkedList

您应该使用array.indexOf(o)

,

索引有点偶然,因为#header{ display:flex; justify-content: space-between; align-items: center; background: rgb(0,64,152); margin: 0; position: fixed; width:100%; } 需要整个O对象; indexOf更容易。 Optional<O>应该是array.indexOf(n)

array.indexOf(o)

如您所见,更新的Stream API消除了一些for / forEach循环的需要。

本文链接:https://www.f2er.com/3124568.html

大家都在问