java 为什么 indexOf 找不到对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9981823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is indexOf failing to find the object?
提问by rishimaharaj
I created an integer list and am trying to return the index of a specific value. The array is 3,8,2,5,1,4,7,6 and I want to return the indexOf(3), which should be 0.
我创建了一个整数列表,并试图返回特定值的索引。数组是 3、8、2、5、1、4、7、6,我想返回 indexOf(3),它应该是 0。
I've tried the following in the Eclipse Java Scrapbook after importing java.util.*:
导入 java.util.* 后,我在 Eclipse Java Scrapbook 中尝试了以下内容:
int[] A = {3,8,2,5,1,4,7,9};
Arrays.asList(A).indexOf(3)
I have also tried:
我也试过:
int[] A = {3,8,2,5,1,4,7,6};
ArrayList<Integer> l = new ArrayList(Arrays.asList(A));
l.indexOf(3)
Both are returning -1. Why? How to get this to work as expected?
两者都返回-1。为什么?如何让它按预期工作?
采纳答案by Eugene Retunsky
It should be Integer[]
not int[]
in order to make it work.
它应该是Integer[]
不int[]
以使其发挥作用。
Integer[] A = {3,8,2,5,1,4,7,9};
final int i = Arrays.asList(A).indexOf(3);
System.out.println("i = " + i); // prints '0'
回答by Louis Wasserman
Arrays.asList(A)
returns a List<int[]>
. This is because it expects an array of objects, not primitive types. Your options include:
Arrays.asList(A)
返回一个List<int[]>
. 这是因为它需要一个对象数组,而不是原始类型。您的选择包括:
- use
Integer[]
instead ofint[]
- inline the array, and let autoboxing take care of it;
Arrays.asList(3,8,2,5,1,4,7,9)
will work fine - use Guava's
Ints.asList(int...)
method to view the primitive array as aList<Integer>
. (Disclosure: I contribute to Guava.) - use Guava's
Ints.indexOf(int[], int)
, which works directly on primitive arrays.
- 使用
Integer[]
代替int[]
- 内联数组,并让自动装箱处理它;
Arrays.asList(3,8,2,5,1,4,7,9)
会正常工作 - 使用Guava 的
Ints.asList(int...)
方法将原始数组视为List<Integer>
. (披露:我为番石榴做出了贡献。) - 使用 Guava's
Ints.indexOf(int[], int)
,它直接作用于原始数组。
回答by Hitham S. AlQadheeb
Do it this way
这样做
Integer[] array = {3,8,2,5,1,4,7,9};
List<Integer> list = Arrays.asList(array);
System.out.println(list.indexOf(8));
asList returns static <T> List<T>
Where T cannot be primitive (int[]).
asList 返回static <T> List<T>
Where T 不能是原始类型 (int[])。