aspose file tools*
The moose likes Java in General and the fly likes Need help about searching on Stack Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Need help about searching on Stack" Watch "Need help about searching on Stack" New topic
Author

Need help about searching on Stack

Marking Fishering
Greenhorn

Joined: Feb 03, 2013
Posts: 6
Hi,

Please find the following code blocks. In TestStack class, I created an instance of an object, and I want to search that instance in the stack. But may be I am doing something wrong which makes it impossible to work. Thanks in advance in anticipation of an early reply!





-------------------------------------------------------------
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41838
    
  63
You're apparently assuming that the search method would compare objects by calling the equals method, but it actually works by using the "==" operator. Calling stack.search(a) would yield the desired result.


Ping & DNS - my free Android networking tools app
Marking Fishering
Greenhorn

Joined: Feb 03, 2013
Posts: 6
Yes, you are right. If I call stack.stack(a), it gives me the desired result. But I want to use a different object with the same values, not the exact same object "a". I am wondering, how can I do that?
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7781
    
  21

Ulf Dittmer wrote:You're apparently assuming that the search method would compare objects by calling the equals method, but it actually works by using the "==" operator...

@Marking: And the reason for that is that the equals() method in your Country class does NOT override Object.equals() (as you'll soon discover if you add the "@Override" annotation to it).

An equals() method MUST have the signature:
public boolean equals(Object s) { ...
if it's supposed to override Object.equals().

My advice: Get into the habit of using @Override for overriding methods; it highlights a lot of subtle errors like this.

Winston

Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Marking Fishering
Greenhorn

Joined: Feb 03, 2013
Posts: 6
Thanks a lot! Suck a tricky error I highly appreciate your replies. Thanks once again.
Dennis Grimbergen
Ranch Hand

Joined: Nov 04, 2009
Posts: 140

Just for your information: If you need a Stack implementation for a serious project, then you should consider writing your own. The reason is that java.util.Stack extends from java.util.Vector. So a Stack is a Vector, and you can perform all things you can on a java.util.List (which is implemented by Vector). Maybe you won't misuse that, but follow up colleagues of you in the project may.


SCJP, SCWCD, SCJD
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Need help about searching on Stack