• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why this method behaves differently?

 
Otsarri Basante
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
/**
* The method "addItem()" receives an item from a
* database. The item has several fields like:
* Reference, Categorie, Name.... and so on.
* I have tried the method with Strings objects instead of
* items and it works, when the String is not found
* "indexOItem" evaluates to �1 else evalutes to 0.
* But when adding item objects retreived from the
* database, it does not work, "indexOfItem" always
* evaluates to �1 even when I try to add an object
* that already is in the Vector.
* Any ideas? Many thanks in advance
*/

public void addItem(Product newItem){
int indexOfItem = items.indexOf(newItem);
if(indexOfItem == -1){
items.addElement(newItem);
}else{
Producto currentItem = (Product)items.elementAt(indexOfItem);
//more code....
}
}
 
Alain Boucher
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to override the equals method in your Product class:

public boolean equals(Object e){
if (e instanceod Product){
//code to check it's equals
return true;
}

return false;
}

It's working with String object because the equals method is override with that class. Because you did not override the equals method it use the Object equals that simply look if the reference id is the same.

Easy one
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
otsarri,

Welcome to JavaRanch!

We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.

We request that display names follow the pattern FIRST_NAME + SPACE + LAST_NAME.

Thanks Pardner! Hope to see you 'round the Ranch!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic