Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index of an element in an array using Java

Tags:

java

arrays

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.

Thanks

like image 545
Somdutta Avatar asked Jul 31 '15 00:07

Somdutta


People also ask

How do you get the index of an item in an array Java?

ArrayUtils. indexOf(array, element) method finds the index of element in array and returns the index.

How do you find the index of an element in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

Can I use index of in an array Java?

There is no indexOf() method for an array in Java, but an ArrayList comes with this method that returns the index of the specified element. To access the indexOf() function, we first create an array of Integer and then convert it to a list using Arrays. asList() .

What is the index of an array in Java?

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on. Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator.


1 Answers

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)

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.

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.

like image 69
Paul Boddington Avatar answered Oct 09 '22 13:10

Paul Boddington