返回数组的位置

时间:2014-04-10 13:04:12

标签: java arrays find

我正在尝试创建一个find方法,它将检查我的PhoneDirectory中的每个条目,并返回与参数中给出的名称匹配的名称的位置。这就是目前的情况:

private String find(String name) {
    for (DirectoryEntry x : theDirectory) {
        if (x.getName().equals(name)) {
            return x.getName();
        }
    }

    return null;
}

但是我会从其他方法中调用我的find函数,而这些方法并不一定要返回名称,而是附加到名称的数字(每个DirectoryEntry都有一个名称和一个telno)。 关于如何返回数组位置而不仅仅是匹配名称的任何帮助都将非常感激。

5 个答案:

答案 0 :(得分:3)

你可以用一个计数器来计算位置

private int find(String name) {
    int i = 0;
    for (DirectoryEntry x : theDirectory) {
        if (x.getName().equals(name)) {
            return i;
        } 
        i++;
    }

    return -1;  // returning -1 if not found
}

或者您可以使用普通for循环而不是foreach

答案 1 :(得分:1)

private String find(String name) {
    int k=0;
    for (DirectoryEntry x : theDirectory) {
        if (x.getName().equals(name)) {
            k++;
            return x.getName();
        }
    }
//k will give you pos
    return null;
}

答案 2 :(得分:0)

如果你想要数组中的位置,请使用常规循环而不是foreach循环。

for (int i=0;i<theDirectory.length;i++) {
DirectoryEntry x = theDirectory[i];
    if (x.getName().equals(name)) {
        return i;
    }
}

答案 3 :(得分:0)

根据theDirectory字段的类型,您可以使用自己的length计数器:

private int find(String name) {
    for (int i = 0; i < theDirectory.length(); i++) {
        DirectoryEntry x = theDirectory[i]; //If it is an Array; for Lists use get etc...
        if (x.getName().equals(name)) {
            return i;
        }
    }

    return -1;
}

答案 4 :(得分:0)

为什么不避免重新发明轮子并改为使用Guava:

private int find(String name) {
    return Iterables.indexOf(theDirectory, new Predicate<DirectoryEntry>() {
        public boolean apply(DirectoryEntry de) {
            return de.getName().equals(name);
        }
    });
}