Better way to find index of item in ArrayList?

Jacksonkr picture Jacksonkr · Dec 9, 2011 · Viewed 257.8k times · Source

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?

Answer

Jon Egeland picture Jon Egeland · Dec 9, 2011

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.