• 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

Comparing Objects with multiple data types within them

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am writing a program that simulates an interactive store. I have made a class called 'Item' that creates an 'Item' object. The item objects contain 3 variables within them: a String (name of item), an int (quantity), and another int (price of item). I have all existing Item objects organized in an ArrayList. Pretty simple.
I have another class called 'Store', which manages the transactions. I have a method in the Store class called 'sellItem'. This method takes two parameters: a String(name) representing the name of the item being sold, and an int(quantity) representing the amount being sold. I want the program to take the name of the item and compare it to names of the existing Item objects in the arrayList and then determine if the item exists in the list. If the item exists, it will remove the quantity from the existing quantity of the item. the problem I'm having is how to only check if the names of the items are the same. Anybody know how to do this?

Ryan Callen
 
Rancher
Posts: 4803
7
Mac OS X VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your use of "the same" is not a good phrase. In Java, things are == or they are equals().
These are separate ideas. == means "is the same thing" whereas if a.equals(b) then a has the same value(s) as b.

To answer your direct question, you implement equals() and hashCode() and usually compareTo()
to compare the things contained in your object.


 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic