This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes Comparing Objects with multiple data types within them Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Comparing Objects with multiple data types within them" Watch "Comparing Objects with multiple data types within them" New topic
Author

Comparing Objects with multiple data types within them

Ryan Callen
Greenhorn

Joined: Nov 29, 2012
Posts: 22
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
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4422
    
    2

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.


 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Comparing Objects with multiple data types within them
 
Similar Threads
arraylist
Complicated Array Problem
Help Client Server implementaion
Arrays: Calling input from other methods and classes
Need help on college work