java indexofany,Java的ArrayList中的IndexOf - 寻找对象指数

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 holder = new ArrayList;

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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值