• Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayLists problem (indexOf)  RSS feed

 
Dillon Colt
Greenhorn
Posts: 11
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello. Yesterday I posted a problem I had with my code and I followed some of the suggestions to make it better. A problem was solved but as you guys may know there are always other problems that emerge. I know my code is not as well organized as I wish he was but I tried to comment stuff so that its easier to understand.
My problem now is that when I try to get the index of an existing object by using indexOf(Object a) it does not find the object even though I know that there is one. I have overriden the equals() in the Coord class to see if it worked but its still not working. So my question is: Why can't I get the index of the object I know is there?
Here is the link to the first post: http://www.coderanch.com/forums/posts/reqResolved/661921 .
The code now is like this:







PS: The commented system outs were used for debugging.
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try overriding the hashcode function too for the Coord class.

When the equals function is overridden, you ought to override the hashcode function too. The reasons? Find out here or here
 
Dave Tolls
Ranch Foreman
Posts: 3068
37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a lot of code.
What List are you having problems with?
Which line are you inserting on?
Which line are you using indexOf that is causing an issue?
 
Dave Tolls
Ranch Foreman
Posts: 3068
37
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hang on, I think I've spotted it:


ships is an ArrayList<Ship> and a is a Coord.
They will never be equal.

Edit: that is, there is never going to be a Ship that is equal to a Coord.
 
Dillon Colt
Greenhorn
Posts: 11
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dave Tolls wrote:Hang on, I think I've spotted it:


ships is an ArrayList<Ship> and a is a Coord.
They will never be equal.

Edit: that is, there is never going to be a Ship that is equal to a Coord.


Man you are a legend! it is solved just like this:


Thank you very much! I guess I should pay more atention to what I write and not take it for granted (I think I do that often).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!