I have a problem with ArrayList. I’m using ArrayList like this:
private ArrayList<Playlist> mPlaylists;
where Playlist is a class inherited from another ArrayList.
I do the following:
p = new Playlist(...some parameters...);
mPlaylists.add(p);
Later, when I use ‘p’ to get the index in the list:
int index = mPlaylists.indexOf(p);
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.
Morten
Edit:
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;
}
New edit:
This WORKS!:
private int getIndex(Playlist playlist) {
for (int i = 0; i < mPlaylists.size(); i++) {
if (mPlaylists.get(i) == playlist) {
return i;
}
}
return -1;
}
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.
This does the trick; Now indexOf() returns the correct object!
Thanks to all contributors!
Most likely your
PlayListmessed up with the default ArrayListequalsimplementation, because the wayindexOfis calculated to something like: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.
EDIT
As per your edit… see? Your
.equals()method is broken.Consider doing a good review and make sure it adheres to the description defined in Object.equals