简体   繁体   English

如何在java中找到数组的索引

[英]how to find index of an array in java

i am trying to use this function but it is giving that index is -1.我正在尝试使用此函数,但它给出的索引为 -1。 so what can i do那我能做什么

int[] veer = {14,25,14,56,15,36,56,77,18,29,49};

int a = Arrays.asList(veer).indexOf(14);

System.out.println("my array at position 14 is :" + (a));

I assume, you want to learn/test what indexOf is doing.我假设,您想学习/测试indexOf正在做什么。 The problem is, that Arrays.asList(veer) returns list containing one element - whole array.问题是, Arrays.asList(veer)返回包含一个元素的列表 - 整个数组。

When I split the code to multiple lines, it is doing:当我将代码拆分为多行时,它正在执行以下操作:

    int[] orig = {14,25,14,56,15,36,56,77,18,29,49};
    List<int[]> origList = Arrays.asList(orig);

and that's why, your indexOf is not able to find 14 in a list, because simply said, there is no integer in list.这就是为什么,您的 indexOf 无法在列表中找到 14,因为简单地说,列表中没有整数。

When you use wrapper type, it works as you might expect当您使用包装器类型时,它会按您的预期工作

    Integer[] veer = {14,25,14,56,15,36,56,77,18,29,49};
    List<Integer> list = Arrays.asList(veer);
    int a = list.indexOf(25); // I changed to 25
    System.out.println("my array at position 25 is :" + a);

which prints index 1.打印索引 1。

To learn about wrapping/unwrapping array, you can read more here Converting Array of Primitives to Array of Containers in Java but changing int[] to Integer[] is simplest in this case (you are not forced by API to accept int[] ).要了解包装/解包数组,您可以在此处阅读更多内容Converting Array of Primitives to Array of Containers in Java但在这种情况下将int[]更改为Integer[]是最简单的(API 不会强迫您接受int[] ) .

In your code在你的代码中

int[] veer = {14,25,14,56,15,36,56,77,18,29,49};

to

Integer[] veer = {14,25,14,56,15,36,56,77,18,29,49};

because indexOf expect a object type since it is primitive it is return as -1(-1 represents not found)因为indexOf期望一个object类型,因为它是原始的,所以它返回为 -1(-1 表示未找到)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM