# Is there a way to get the index of an item in array

**URL:** https://discourse.processing.org/t/is-there-a-way-to-get-the-index-of-an-item-in-array/27113
**Category:** Beginners
**Created:** [January 16, 2021, 2:11pm UTC](https://discourse.processing.org/t/is-there-a-way-to-get-the-index-of-an-item-in-array/27113 "2021-01-16T14:11:29Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![CodeMasterX](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/codemasterx/32/2942_2.png) [@CodeMasterX](https://discourse.processing.org/u/CodeMasterX)
#### Post date: [January 16, 2021, 2:11pm UTC](https://discourse.processing.org/t/is-there-a-way-to-get-the-index-of-an-item-in-array/27113/1 "2021-01-16T14:11:30Z")

</div>

Is there a way to get the index of an item in an array of a given ArrayList?  
I know you could use

```auto
int test(String item) {
    for(int i = 0; i < items.size() && items.contains(item); i++) if(item == items.get(i)) return(i);
    return -1;
}

```

but is it the best way to do it?

Is there something like

```auto
int v = items.getIndex(item); //?

```

---

<div class="post-metadata">

### Author: ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)
#### Post date: [January 16, 2021, 2:55pm UTC](https://discourse.processing.org/t/is-there-a-way-to-get-the-index-of-an-item-in-array/27113/2 "2021-01-16T14:55:54Z")

</div>

maybe indexOf?

see [ArrayList (Java Platform SE 8 )](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html)

This link is from the reference [ArrayList \ Language (API) \ Processing 3+](https://www.processing.org/reference/ArrayList.html)

---

<div class="post-metadata">

### Author: ![SNICKRS](https://avatars.discourse-cdn.com/v4/letter/s/43a26b/32.png) [@SNICKRS](https://discourse.processing.org/u/SNICKRS)
#### Post date: [January 17, 2021, 2:57am UTC](https://discourse.processing.org/t/is-there-a-way-to-get-the-index-of-an-item-in-array/27113/3 "2021-01-17T02:57:29Z")

</div>

Yes, it is indexOf. You can also make a method that gets the position, like this:

```auto
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(0);
numbers.add(1);
numbers.add(2);
//first method
int getIndex (int number) {
  for (int i = 0; i < numbers.size(); i++) {
    if (numbers.get(i) == number) {
      return i;
    }
  }
  return 0;
}
//second method
int index = numbers.indexOf(1);

```
