• Post Reply Bookmark Topic Watch Topic
  • New Topic

using ArrayList contains method  RSS feed

 
Patricia Smith
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm trying to use the contains method of ArrayList but with no success. My application is this: I'm trying to work through a maze by creating my own stack object and pushing locations onto the stack and then backtracking or popping of locations when I get jammed in a corner with no way out.


So, I have a class called CS127BStack which has a method called contains. Here's the contains method:


You'll notice that I commented out the first try at just using ArrayList's built in contains method. Both ways didn't work.
The LocDirObject that this method refers to is another class I made which holds a row number, a column number and a String (one character really).

Here's that code:


It compiles and runs but always gives me false for whether the stack contains a specific LocDirObject even if I have just pushed it onto the stack.
[ March 20, 2005: Message edited by: Patricia Smith ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Well, I can tell you why the built-in contains() isn't working for you, but the code you've shown looks fine and ought to work (unless there's some very subtle error I'm missing, or it isn't being called at the right time or in the right way.)

The ArrayList.contains() method uses the equals() method to compare the objects it contains. Every class has an equals() method because it's inherited from Object. The default version returns the result thisObject == otherObject -- i.e., it's only true if the two objects are in fact the same object. To make contains() work, you'd need to override equals() to make it mean "equivalent", as defined in the code you've shown.

If you do this, remember that the signature is

boolean equals(Object)

You have to accept an Object argument and cast it to the type of the class. If you change the argument type you'll be overloading rather than overriding.
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, the reason it isn't working is you haven't overriden the equals method.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In EFH's defense , the LocDirObject code hadn't been posted when he posted earlier. Patricia, if you have further additions of modifications to make, it would be a good idea to post them in new posts in this same thread. Otherwise you create confusion for anyone trying to read the subsequent comments. Thanks.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!