Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList IndexOf - Finding Object Index

Tags:

java

arraylist

Lets say I have a class

public class Data{
    public int k;
    public int l;
    public Data(int k, int l){
      this.k = k; 
      this.l = l;
    }
    public boolean equals(Date m){
      if(this.k == m.k && this.l = m.l)
           return true;
      return false;
    }
}

And I add a few Data objects to a ArrayList:

ArrayList<Data> holder = new ArrayList<Data>;
Data one = new Data(0,0);
Data two = new Data(0,4);
Data three = new Data(0,5);

Why does indexOf not find this?:

holder.indexOf(new Data(0,4)); //returns -1

Is indexOf any better than going through the whole array list myself? Or am I missing something.

like image 781
p1001 Avatar asked Jul 08 '13 04:07

p1001


People also ask

How do you find the index of an object in an ArrayList?

The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().

Can you use indexOf on ArrayList in Java?

indexOf() in Java. The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

How do I check if an ArrayList contains an index?

int indexOf(Object o) indexOf(Object o) method is used to search for a specified element in ArrayList and return its index. If it doesn't find the element, then it returns -1. indexOf() method searches element from the 0th index to ArrayList's size.

What index does ArrayList start?

The ArrayList index starts at 0 just like arrays, but instead of using the square brackets [] to access elements, you use the get(index) to get the value at the index and set(index,value) to set the element at an index to a new value.


1 Answers

The indexOf() method does go through the entire list. Here's an excerpt from Java 7 source code:

public int indexOf(Object o) {
    if (o == null) {
        for (int i = 0; i < size; i++)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

It'd be better to let Java go through it than write it yourself. Just make sure that your equals method is sufficient at finding the object you want. You'll also want to override hashCode() as well.

I won't write your equals method out, but I would recommend that you at least:

  • Check for null
  • Test if the instances you're comparing are the same
  • You don't need to do if(boolean_expr) { return true; }; just return the boolean expression.
  • Make sure you're actually overriding your equals method - the signature of that requires an Object parameter, not Date.
like image 133
Makoto Avatar answered Sep 28 '22 09:09

Makoto