Java的Array indexOf在哪里?我必须遗漏一些非常明显的东西,但我已经遍地搜索过,找不到这种方法。
3 回答

饮歌长啸
TA贡献1951条经验 获得超3个赞
使用Arrays
实用程序类有两种方法可以实现此目的。
如果数组未排序且不是基元数组:
java.util.Arrays.asList(theArray).indexOf(o)
如果数组是基元并且没有排序,那么应该使用其他答案之一提供的解决方案,例如KeremBaydoğan,Andrew McKinlay或Mishax。即使theArray
是原始代码(可能发出警告),上面的代码也会编译,但是你会得到完全错误的结果。
如果数组已排序,您可以使用二进制搜索来获得性能:
java.util.Arrays.binarySearch(theArray, o)

守着一只汪
TA贡献1872条经验 获得超3个赞
数组没有indexOf()
方法。
也许这个Apache Commons Lang ArrayUtils
方法就是你想要的
import org.apache.commons.lang3.ArrayUtils;String[] colours = { "Red", "Orange", "Yellow", "Green" };int indexOfYellow = ArrayUtils.indexOf(colours, "Yellow");

RISEBY
TA贡献1856条经验 获得超5个赞
空无一人。要么使用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;}
*您可以使用您的阵列制作一个 Arrays#asList()
添加回答
举报
0/150
提交
取消