Back

Explore Courses Blog Tutorials Interview Questions
+11 votes
4 views
in Java by (1.1k points)
edited by

What is indexOf method in Java, I can't seem to find it anywhere. Also how do I use it?

2 Answers

+13 votes
by (13.2k points)
edited by

There is no indexof method in Java. There is Array.Indexof method in C# but java has no such method. The method of indexOf is defined in the java docs .

Now, If our array is sorted, then it is easy, because the Arrays class defines a series of overloads of the binarySearch method that will find the index of the element, like shown below.

java.util.Arrays.binarySearch(Array, o)

But if the array is not sorted, then we have 2 further cases,

  1. If the array is not sorted and it is not array of primitives, then using Array utility class we can use the indexOf method defined in there.

java.util.Arrays.asList(theArray).indexOf(o)
  1. If the array is not sorted and it array of primitives, then there is no help that you can get from java APIs and you will have to write it on your own, or check out Guava's Chars.indexOf, it lets you get the index in an array.

0 votes
by (40.7k points)

There's no indexOf() method in Array as such in Java.

I think you are looking for Apache Commons Lang ArrayUtils method, which is as follows:

import org.apache.commons.lang3.ArrayUtils;

String[] colours = { "Red", "Orange", "Yellow", "Green" };

int indexOfYellow = ArrayUtils.indexOf(colours, "Yellow");

For more information on ArrayUtils method you can refer to this: 

http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html

Interested in learning Java end to end? Go through this Java video for beginners!

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 23, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...