96

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?

Jacksonkr
  • 31,583
  • 39
  • 180
  • 284
  • 2
    This code is likely flawed: use of `==` will yield incorrect results in most cases. –  Dec 08 '11 at 23:18
  • 3
    Remember, you can't compare strings with '==', you have to use String.equals(String str) – MrZander Dec 08 '11 at 23:20
  • 5
    @MrZander Sure you can compare them with `==` ... it just not be the right kind of comparison ;-) –  Dec 08 '11 at 23:21
  • You can tell I'm still new to Java.. is `String.equals` more like what a `===` might be in a language like JavaScript? eg. checks against value AND type? – Jacksonkr Dec 09 '11 at 00:16
  • 3
    **No.** `==` is *object-identity* and it means **"is the same object"**. (This view holds true for primitive values as well as reference types, if you consider there is only one number with the value 42 or char 'x', etc). `Object.equals` is a *virtual method* defined for all object instances and it means **"has the same value"**, as all class types extend Object, and should be used for all *object-equality* tests. **There are many questions at cover `==` vs `Object.equals` and this is a very important concept to understand!** For instance, this is false: `"hello" == new String("hello")`! Doh! –  Dec 09 '11 at 01:04
  • See http://stackoverflow.com/questions/767372/java-string-equals-versus and related questions. –  Dec 09 '11 at 01:10

8 Answers8

212

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.

Jacksonkr
  • 31,583
  • 39
  • 180
  • 284
Jon Egeland
  • 12,470
  • 8
  • 47
  • 62
  • 3
    It is no "fast"er in terms of complexity than the code posted, although it may be implemented more efficiently. Also, indexOf will react slightly differently here: the original code [incorrectly] uses `==` while indexOf uses `equals()`. –  Dec 08 '11 at 23:19
  • In fact, it's almost the same code exactly (at least in the Sun Java 6 code I have), except that they start it with an if-else branch that handles null separately. – yshavit Dec 08 '11 at 23:47
  • It's wired old arrays and List<> have FindIndex() method but the API changes in the middle for ArrayList :D – boctulus Dec 31 '14 at 22:31
17
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: List Index : 7

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

Done

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
  • How i can make the vise versa of this, for your solution your input is **H** and you get the position of **H**, Suppose if my input is the Index of **7** how i can get the the String value of that index. Thank You – Jimale Abdi May 03 '19 at 23:39
  • 1
    @JimaleAbdi Do yourArrayList.get(7). 7 is your position. – Hiren Patel May 04 '19 at 02:19
7

If your List is 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 is sound, fwiw (other than the == others have pointed out).

yshavit
  • 42,327
  • 7
  • 87
  • 124
4

Java API specifies two methods you could use: indexOf(Object obj) and lastIndexOf(Object obj). The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.

danca
  • 509
  • 4
  • 11
3

There is indeed a fancy shmancy native function in java you should leverage.

ArrayList has an instance method called

indexOf(Object o)

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

You would be able to call it on _categories as follows:

_categories.indexOf("camels")

I have no experience with programming for Android - but this would work for a standard Java application.

Good luck.

rustybeanstalk
  • 2,722
  • 9
  • 37
  • 57
2

the best solution here

class Category(var Id: Int,var Name: String)
arrayList is Category list
val selectedPositon=arrayList.map { x->x.Id }.indexOf(Category_Id)
spinner_update_categories.setSelection(selectedPositon)
1

Use indexOf() method to find first occurrence of the element in the collection.

Vasu Dev Garg
  • 121
  • 1
  • 15
0

The best way to find the position of item in the list is by using Collections interface,

Eg,

List<Integer> sampleList = Arrays.asList(10,45,56,35,6,7);
Collections.binarySearch(sampleList, 56);

Output : 2