使用Java数组中元素的索引 [英] Index of an element in an array using Java
问题描述
以下Java代码返回-1.我认为应该返回3.
The following code in Java return -1. I thought that it should return 3.
int[] array = {1,2,3,4,5,6};
System.out.println(Arrays.asList(array).indexOf(4));
能帮我了解一下此功能的工作原理吗.
Can you help me understand how this function works.
谢谢
推荐答案
在Java 5之前,Arrays.asList
用于接受Object[]
.当将泛型和varargs引入该语言时,它更改为
Before Java 5, Arrays.asList
used to accept an Object[]
. When generics and varargs were introduced into the language this was changed to
public static <T> List<T> asList(T... arr)
在您的示例中,T
不能为int
,因为int
是原始类型.不幸的是,签名匹配的T
等于int[]
,这是一种引用类型.结果是您最终得到的是包含数组而不是整数的List
的List
.
In your example, T
cannot be int
because int
is a primitive type. Unfortunately, the signature matches with T
equal to int[]
instead, which is a reference type. The result is that you end up with a List
containing an array, not a List
of integers.
在Java 4中,由于int[]
不是Object[]
,因此不会编译您的代码.不编译比产生奇怪的结果更可取.在有效Java中,乔什·布洛赫(Josh Bloch)说,将asList
改装为varargs方法是一个错误.
In Java 4, your code would not have compiled because an int[]
is not an Object[]
. Not compiling is preferable to producing a strange result, and in Effective Java, Josh Bloch says retrofitting asList
to be a varargs method was a mistake.
这篇关于使用Java数组中元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!