ArrayList indexOf() 返回错误的索引? [英] ArrayList indexOf() returns wrong index?
问题描述
我对 ArrayList 有问题.我像这样使用 ArrayList:
I have a problem with ArrayList. I'm using ArrayList like this:
private ArrayList<Playlist> mPlaylists;
其中 Playlist 是从另一个 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;
}
解决方案:按照建议,我将 Playlist 类更改为不从 ArrayList 继承,而是私下保留一个实例.原来我只需要实现 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!
感谢所有贡献者!
推荐答案
很可能你的 PlayList
与默认的 ArrayList equals
实现搞砸了,因为 indexOf
是 计算 类似于:
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.
考虑进行良好的审查并确保它符合 Object.equals
Consider doing a good review and make sure it adheres to the description defined in Object.equals
这篇关于ArrayList indexOf() 返回错误的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!