I am trying to learn Java. The Eric Roberts text, "The Art and Science of Java" has a programming assignment where we simulate a flight booking console. I wanted to 'class it up' by using a City class where just a City String would do. It only has one field, name
, which is a String, but I am trying to learn how to use classes.
Anyway, so then I had to override the equals method in the City class to avoid getting duplicates. So then I had to override the hashCode method.
Now my HashMap<City,ArrayList<Flight>>
isn't working. It can't find certain values and it still permits duplicate keys.
My City equals
and hashCode
overrides are as follows. Can anybody see why my HashMap is going wrong?
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object that) {
// TODO Auto-generated method stub
if ( this == that ) return true;
if ( !( that instanceof City) ) return false;
City aThat = (City) that;
return (name == aThat.name );
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return name.hashCode();
}