我一定是错过了一些非常明显的东西,但我已经搜索了所有,不能找到这个方法。


当前回答

Java数组列表有一个indexOf方法。Java数组没有这样的方法。

其他回答

List接口有一个indexOf()方法,您可以使用array的asList()方法从数组中获取List。除此之外,Array本身没有这样的方法。它确实有一个用于排序数组的binarySearch()方法。

在java数组中没有直接的indexOf函数。

Jeffrey Hantin的答案很好,但它有一些限制,如果它是这个做这个或那个…

你可以编写自己的扩展方法,它总是以你想要的方式工作。

Lists.indexOf(array, x -> item == x); // compare in the way you want

这是您的分机号码

public final class Lists {
    private Lists() {
    }

    public static <T> int indexOf(T[] array, Predicate<T> predicate) {
        for (int i = 0; i < array.length; i++) {
            if (predicate.test(array[i])) return i;
        }
        return -1;
    }

    public static <T> int indexOf(List<T> list, Predicate<T> predicate) {
        for (int i = 0; i < list.size(); i++) {
            if (predicate.test(list.get(i))) return i;
        }
        return -1;
    }

    public interface Predicate<T> {
        boolean test(T t);
    }
}

没有。或者使用java.util。List*,或者你可以自己写indexOf():

public static <T> int indexOf(T needle, T[] haystack)
{
    for (int i=0; i<haystack.length; i++)
    {
        if (haystack[i] != null && haystack[i].equals(needle)
            || needle == null && haystack[i] == null) return i;
    }

    return -1;
}

*你可以使用数组#asList()创建一个数组

数组没有indexOf()方法。

也许这个Apache Commons Lang ArrayUtils方法就是您要找的

import org.apache.commons.lang3.ArrayUtils;

String[] colours = { "Red", "Orange", "Yellow", "Green" };

int indexOfYellow = ArrayUtils.indexOf(colours, "Yellow");