Best way to find an index of an element in an ArrayList?

For Android application, I have the following functions

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 this the best way to write a function to get the position of an element? Or is there a built-in shmancy function in java that I should use?

+78
java arraylist for-loop
Dec 08 '11 at 23:09
source share
5 answers

ArrayList has an indexOf() method. Check the API again, 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 what your method returns, quickly.

+179
Dec 08 '11 at 23:12
source share
 ArrayList<String> alphabetList = new ArrayList<String>(); alphabetList.add("A"); // 0 index alphabetList.add("B"); // 1 index alphabetList.add("C"); // 2 index alphabetList.add("D"); // 3 index alphabetList.add("E"); // 4 index alphabetList.add("F"); // 5 index alphabetList.add("G"); // 6 index alphabetList.add("H"); // 7 index alphabetList.add("I"); // 8 index int position = -1; position = alphabetList.indexOf("H"); if (position == -1) { Log.e(TAG, "Object not found in List"); } else { Log.i(TAG, "" + position); } 

Output: Index List: 7

If you pass H , it will return 7 , if you pass J , it will return -1 as we defined the default value -1.

Done

+14
May 19 '15 at 9:49
source share

If your List sorted and has good random access (as ArrayList does), you should look into Collections.binarySearch . Otherwise, you should use List.indexOf , as others have pointed out.

But your algorithm sounds fwiw (except for pointers == ).

+6
Dec 08 '11 at 23:18
source share

There really is a fantastic shmancy function in java that you should use.

ArrayList has an instance method called

indexOf(Object o)

(http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html)

You can call it _categories as follows:

_categories.indexOf("camels")

I have no Android programming experience, but this will work for a standard Java application.

Good luck.

+3
Dec 08 '11 at 23:15
source share

The Java API defines two methods that you could use: indexOf(Object obj) and lastIndexOf(Object obj) . The first returns the index of the element if it is found, -1 otherwise. The second returns the last index, which will look like a search in the list back.

+2
Dec 08 '11 at 23:17
source share



All Articles