• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why this method behaves differently?

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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....
}
}
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic