Reputation: 27
I have Kitchen
and each Product
s in my Kitchen
has an expiring date,
This is with x
days to initialize after creation
x = for wine 3 years
for cheese 10 days
for eggs 2 days
The inquiry should be from the Kitchen
- which product in the kitchen expires first?
Please anyone ready to help me implement this or give me a guideline? I am just 6 weeks into the world of Java programming, challenging myself.
Upvotes: 0
Views: 143
Reputation: 718718
The most appropriate data structure is a PriorityQueue
with a Comparator
class that orders Product
objects by expiry date.
If you wanted a more generic class, then a TreeSet
(with the same comparator class) would do the job. (But there is a snag. Your comparator needs a tie-breaker so that two different Product
objects with the same expiry date are not treated as equal. If you don't do this, then one of the Product
objects will be treated as a duplicate, and not added to the set.)
Upvotes: 7
Reputation: 1755
You can do this in a couple ways but the simplest would be
1) Kitchen
class can have a list of Products
each product has an expiry age (days) and you will need a purchase / manufacture date.
2)Add a helper method to the product which rolls the purchase / manufacture date by the expiry age.
3) Implement comparable on your product and you can get an ordered list
you can find an example of how to implement comparable here
EDIT
If you wanted more than just order by expiry; consider using Visitor pattern to retrive other information such as product by least quantity.
Upvotes: 0
Reputation: 90879
Like you explained youself -
Product class -
class Product {
private int daysTillExpiration = 0;
public int getDaysTillExpiration() {
return daysTillExpiration;
}
public void setDaysTillExpiration(int daysTillExpiration) {
this.daysTillExpiration = daysTillExpiration;
}
}
Kitchen class -
class Kitchen {
private ArrayList<Product> products;
public Product inquire() {
int min = products.get(0).getDaysTillExpiration();
Product res = products.get(0);
for(Product prod : products) {
if(prod.getDaysTillExpiration() < min) {
min = prod.getDaysTillExpiration();
res = prod;
}
}
return res;
}
}
Upvotes: 0
Reputation: 741
I'm assuming what you are doing is creating a kitchen object and then you are creating food and adding them into your already created kitchen object.
The "adding them to your kitchen" part is where you can use a collection to store the data.
List<Product> list = new ArrayList<Product>();
Product is just an interface that allows you to add the items to the collection easily, then you can just get the collection and iterate through the elements.
If you don't understand any of that, Google why/how you use array lists, look into generics (https://docs.oracle.com/javase/tutorial/java/generics/why.html), then Google how to get an object from a class (the ArrayList from your kitchen class), then Google how to iterate through an ArrayList.
Upvotes: 0