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?
The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With