0

I have some troubles in dealing with this "search()" function that i wrote. Well, i need to check if an object already exists in my stack. My object looks like this:

 Boat [mLeft=[0, 0, 0], boat=L, mRight=[0, C, V]]

And my stack is something like this:

  Boat [mLeft=[0, 0, 0], boat=L, mRight=[0, C, V]]
  Boat [mLeft=[0, 0, 0], boat=C, mRight=[L, 0, V]]
  Boat [mLeft=[0, 0, 0], boat=V, mRight=[L, C, 0]]
  Boat [mLeft=[0, 0, 0], boat=0, mRight=[L, C, V]]

And this is my "search" function:

  public boolean search(Boat b){
    boolean r=false;
    for(int i=0;i<btStack.size();i++)
    {
        if(btStack.elementAt(i).equals(b))
        {
            r = true;               
        }
    }
    return r;
}

This is never true...and i don't have any idea why. Can you help?Thanks

Dianna
  • 392
  • 4
  • 15
  • if(btStack.elementAt(i).equals(b)) { return true; } there's no reason to loop further once you've found the element. – ignis Oct 27 '12 at 16:44

1 Answers1

3

Default equals behavior of object class compares equality based on references.You need to override equals in Boat class. With equals you should also override hashcode

@Override
public boolean equals(Object obj) {
    if (obj == null)
        return false;
    if (!(obj instanceof Boat))
        return false;

    Boat b = (Boat)obj;
    return  b.someproperty==this.someproperty;//Assuming someproperty is primitive
}

References:

  1. Equals and Hash Code
  2. Overriding equals and hashCode in Java
Community
  • 1
  • 1
Amit Deshpande
  • 18,407
  • 4
  • 42
  • 69