Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to find index of item in ArrayList?

For an Android app, I have the following functionality

private ArrayList<String> _categories; // eg ["horses","camels"[,etc]]  private int getCategoryPos(String category) {     for(int i = 0; i < this._categories.size(); ++i) {         if(this._categories.get(i) == category) return i;     }      return -1; } 

Is that the "best" way to write a function for getting an element's position? Or is there a fancy shmancy native function in java the I should leverage?

like image 743
Jacksonkr Avatar asked Dec 08 '11 23:12

Jacksonkr


People also ask

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

The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().

Can we get index in ArrayList?

The get() method of ArrayList in Java is used to get the element of a specified index within the list. Parameter: Index of the elements to be returned. It is of data-type int. Return Type: The element at the specified index in the given list.

How do you find the index of an item in a list in Java?

The standard solution to find the index of an element in a List is using the indexOf() method. It returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.


1 Answers

ArrayList has a indexOf() method. Check the API for more, but here's how it works:

private ArrayList<String> _categories; // Initialize all this stuff  private int getCategoryPos(String category) {   return _categories.indexOf(category); } 

indexOf() will return exactly what your method returns, fast.

like image 113
Jon Egeland Avatar answered Oct 14 '22 16:10

Jon Egeland