Java的ArrayList中的IndexOf - 寻找对象指数 [英] Java ArrayList IndexOf - Finding Object Index

查看:361
本文介绍了Java的ArrayList中的IndexOf - 寻找对象指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有一个类

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

和我添加了一些数据对象的ArrayList一个:

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

为什么的indexOf找不到这样的:

Why does indexOf not find this?:

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

时的indexOf比任何经历的整个数组列出自己更好?还是我失去了一些东西。

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

推荐答案

的indexOf()方法的通过整个列表。下面是从Java 7的源$ C ​​$ C的摘录:

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

这将会是更好地让Java的经历比你自己写吧。只要确保你的等于方法是找到你想要的对象就足够了。您还需要重写散code()以及

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:


  • 检查空

  • 测试,如果你要比较的实例是相同

  • 您不需要做如果(boolean_expr){返回true; } ;只是返回布尔前pression。

  • 确保您实际上是覆盖你的等于方法 - 那签名需要一个对象参数,不日期

  • 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.

这篇关于Java的ArrayList中的IndexOf - 寻找对象指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆