Java ArrayList IndexOf - Finding Object Index

后端 未结 4 1385
独厮守ぢ
独厮守ぢ 2020-12-05 19:56

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;
    }
             


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 20:39

    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.

提交回复
热议问题