It's not a secret anymore!
The moose likes Java in General and the fly likes Why this method behaves differently? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why this method behaves differently?" Watch "Why this method behaves differently?" New topic

Why this method behaves differently?

Otsarri Basante

Joined: Jun 29, 2004
Posts: 1
* 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){
Producto currentItem = (Product)items.elementAt(indexOfItem);
//more code....
Alain Boucher
Ranch Hand

Joined: Feb 25, 2003
Posts: 51
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

Alain Boucher<br />Spare-Brain Consultants Inc.<br />SCJ2P,SCWCD,
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023

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!

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: Why this method behaves differently?
jQuery in Action, 3rd edition