ArrayList中的indexOf()返回错误的指标? [英] ArrayList indexOf() returns wrong index?

查看:583
本文介绍了ArrayList中的indexOf()返回错误的指标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ArrayList的一个问题。我使用的ArrayList是这样的:

I have a problem with ArrayList. I'm using ArrayList like this:

private ArrayList<Playlist> mPlaylists;

其中,播放列表是一个类从另一个ArrayList的继承。 我做到以下几点:

where Playlist is a class inherited from another ArrayList. I do the following:

p = new Playlist(...some parameters...);
mPlaylists.add(p);

后来,当我用P来获取索引列表:

Later, when I use 'p' to get the index in the list:

int index = mPlaylists.indexOf(p);

1的索引被返回,即使该列表的检查清楚地表明,它的索引4

an index of '1' is returned, even though inspection of the list clearly shows that it's index '4'.

是否有人知道为什么会失败? 谢谢你。

Does anybody know why this fails? Thanks.

B.R。 莫滕

编辑: 没有的indexOf()同样的问题,使用equals():

Same problem without indexOf(), using equals():

private int GetIndex(Playlist playlist) {
    for (int i = 0; i < mPlaylists.size(); i++) {
        if (mPlaylists.get(i).equals(playlist)) {
            return i;
        }
    }
    return -1;
}

新的编辑: 这个作品:

private int getIndex(Playlist playlist) {
    for (int i = 0; i < mPlaylists.size(); i++) {
        if (mPlaylists.get(i) == playlist) {
            return i;
        }
    }
    return -1;
}

解决方法: 作为建议,我改变了播放列表类从ArrayList中不enherit,而是保持一个实例私人。原来,我只需要实现4 ArrayList的方法。

Solution: As suggested, I changed the Playlist class to not enherit from ArrayList, but rather keeping an instance privately. It turned out that I only had to implement 4 ArrayList methods.

这是卓有成效的;现在的indexOf()返回正确的对象!

This does the trick; Now indexOf() returns the correct object!

感谢所有贡献者!

推荐答案

最有可能你的播放列表搞砸了默认的ArrayList 等于的实施,因为这样的indexOf 是<一个href="http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#indexOf%28java.lang.Object%29">calculated 以是这样的:

Most likely your PlayList messed up with the default ArrayList equals implementation, because the way indexOf is calculated to something like:

indexOf(Object o) 
   if( o == null ) then iterate until null is found and return that index
   if( o != null ) iterate until o.equals( array[i] ) is found and return taht index
   else return -1 
end

所以,你正在做一些有趣的事情与你的.equals方法或您不小心插入其它元素在列表中,当你认为它是在最后。

So, you are doing something funny with your .equals method or your are accidentally inserting another element in the list when you think it is at the end.

修改

根据你的编辑......看到了什么?你的 .equals()方法被打破。

As per your edit... see? Your .equals() method is broken.

考虑做一个很好的审查,并确保它坚持在<定义的描述href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals%28java.lang.Object%29">Object.equals

Consider doing a good review and make sure it adheres to the description defined in Object.equals

这篇关于ArrayList中的indexOf()返回错误的指标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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