• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need help about searching on Stack

 
Marking Fishering
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42968
73
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Marking Fishering
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 10422
63
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Marking Fishering
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot! Suck a tricky error I highly appreciate your replies. Thanks once again.
 
Dennis Grimbergen
Ranch Hand
Posts: 159
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic