i have an ArrayList called e.g. Fridge
List<Food> fridge = new ArrayList<Food>();
An simple explanation:
Because i want to keep my fridge organized i want to put my food into seperate drawers.
I already have the Classes Meat, Fruit and Bread.
The point i am struggling with is to create new ArrayList's which picture the different drawers.
My goal is to have the fridge List a parent list and meat,fruit,bread as children of this list.
fridge (Parent)
---meat (Child)
---fruit (Child)
---bread (Child)
Do you have any ideas how to realize this ?
I'm glad for any help
EDIT:
The Objects i want to add to thesublists contain informations such as String obj.name; double obj.weight; double obj.price; i want to add the objects to the sublists and be able to read the sublists out again.
"fridge" shouldn't be a simple ArrayList since it needs to have its own more complex state and behaviors. Instead it should be a full fledged class and should contain 3 (or more) ArrayLists: meatList, fruitList, and breadList, as well as methods to put items in each of the lists, as well as methods of retrieving items, and methods for printing or displaying items.
Likewise Food can have subclasses for Meat, Fruit and Bread (although per Good Housekeeping, one shouldn't put bread in a refrigerator -- it causes condensation and sogginess).
I don´t get 100%ly what you want but I guess you just want to store your Food data.
1.)
Just make an List of Lists:
ArrayList<ArrayList<Food>> fridge;
where every inner List presents an drawer. Meat, Fruit, etc. will be an Subclass of Food.
2.)
make a Map with an key as the "name" of the drawer
HashMap<String, ArrayList<Food>> fridge;
With that you can easily get the "drawers" content. However that doesn´t change much to the above.
3.)
Make an Fridge class which stores all your stuff. And since an Fridge can hold more than just Food make an interface which defines what properties an Thing has which can be stored.
interface Storable{
String getName(); int getId(); String getType(); void use();
}....//whatever everything which will be stored has.
class Fridge{
HashMap<String, ArrayList<Storable>> contents;
void add(Storable food){
this.contents.put(food.getType, food); //or instead of #getType use the class of the food.
}
and then your Food, Meat, etc:
class Food implements Storable{
//implement the inherited Methods
}
Then you have again some choices, like make for each type an class (Meat, Bread, etc) or just make in Food an field "type" which describes what it is. It highly depends on your "mental model".
You are getting your "mental" model wrong. A fridge is much more than just a List that contains other lists.
Just imagine the "real fridge" in your kitchen. There is much more to it than just some lists (sorted by content)!
Thus you should first try to figure for yourself what the purpose of a "fridge" within your mental model is. Which behavior (interface) should it offer to users of that class?!
Example: is it really relevant that a fridge knows its content by "type"? Or would it matter more how entries in that fridge are physically ordered?
So besides the excellent answer from Hovercraft you might want to step back even further in order to really define what the terms you are using should mean within your program!
Related
I got a question. Is there a simple solution to iterate over the list that is inside of a list and inside of a list again?
So my point is I have few of lists inside of each other (based on xml unmarshall) and I sometimes do not know how deep is the structure.
Exsample:
class Car{
private List<Door>
}
class Door{
private List<Parts>
}
class Parts{
private List<Some1>
}
}
class Some1{
private List<Some2>
}
So how can iterate from Car to Some2 without knowing if there is a list or is empty in a "good way"? I mean without 5-times nested "for" loops mixed up with another 6 "if's".
DeeV makes a good suggestion about each class iterating over their respective lists.
As a client using the Car class, you may want to get all the Some2s that it contains. If you do this:
car.getDoors().getParts().get...
you expose the internals of the Car class. A much cleaner solution would be to have the following method in the Car class:
public List<Some2> getSome2s()
This way, if the internals of Car change (perhaps using a different Collection type) your client code will not break as long as a list of Some2s is still returned.
There is no easier way than nested for loops. If you want more speed try using different structures like Maps.
First implement composite pattern with your classes after you'll be able to recursive to leafs and aggregate them in a list.
I want to store three values in a 2D type in java. I know that we can use List and ArrayList for storing 1D values but I need to store more than one field in a specific record. For example i have to enter the details for multiple columns i.e. (1,1),(1,2),(1,3) for details such aaaa, bbbb, cccc for a person and store them in one single row(which may consist of values which are other than string type). It should run in a loop and once details of a person is stored, it should store (2,1),(2,2),(2,3) i.e. again for a new person. How to do that?
And later on, how to retrieve and send the complete set to database together? Please help..
What you might want to do is to create a class that holds all of the information you want to keep related to a single record if it represents a concrete thing and use the List and ArrayList to store those.
What I mean by concrete thing is something that has a finite set of information that will stay the same over each object.
Something like:
public class Person
{
String name;
Integer age;
// etc...
}
This gives you two advantages over using something like a 2D array. First, it will make reading your code easier, since instead of having to remember that arrayName[x][0] is whatever you decide the first field is, you can access it using something like listItem.attributeName. The second advantage is that you can abstract out any common datahandling tasks as class methods instead of having to bloat your main class with it.
So what I am trying to do is create a code that lists music artists names using user input.
It has to have multiple classes so I will have a main class, and a class for each decade of music.
Music.java
six.java
seven.java
eight.java
In these classes I need to create string arrays that contain artist names, and be able to generate the entire list once prompted.
To give a better idea of how the code will run it would go something like:
Choose a decade of music:
70's
Choose a genre of music:
Rock
Choices are: Rolling Stones, Talking Heads, etc.
That's all I need it to do but I'm getting stuck on what to put in the main class "music.java" to get it to read the other classes and furthermore how to write the decade classes.
I understand I don't have much to offer you guys here but any help would be appreciated.
In general terms, you need a class in this rough form:
public class Artist
{
public int decade
public string genre
}
Then some code to use it:
... code to retrieve some kind of collection (e.g. an array or list), of artists as Artist objects (you'll need to do this by retrieving the artist data from a database)
... code to iterate through the collection to do what you want with it:
I would only have a class named Band and a container class for all bands named BandRegister. The Band would hold a Set of values representing the decade, which are added using associateWithDecate(int decade) method:
Class BandRegister:
Map<Integer, Set<Band>) decadeMap = new HahMap...
public addBand(band);
{
//define logic for adding the decade and band to decadeMap
}
Class Band:
Set<Integer> decades = ...
public associateWithDecate(int decade)
{
//add decade to decades if not already included
}
In Main:
BandRegister breg = new BandRegister();
Band stones = new Band("Rolling Stones");
stones.associateWithDecate(60);
stones.associateWithDecate(70);
stones.associateWithDecate(70);
stones.associateWithDecate(90);
stones.associateWithDecate(0);
stones.associateWithDecate(10);
breg.addband(stones);
That way, you can get a listing of decades for each band and also in the register you can get a listing of bands for each decade
I'm working on a Java program where I can keep track of my employee payroll. There are two types of employees, hourly and salary.
I have a while loop asking for the input and creating the objects so that I can add as many or as few employees as I want.
When I create my object from my class, I simply use:
HourlyEmployee employee = new HourlyEmployee(type, name, hours, rate);
However, if this is in a while loop, will I be creating several instances of the class type HourlyEmployee with the same name "employee"? Does it even matter if they have the same name (I just want to display the information for each employee on the screen later).
If so, how do I write my code so that the name of each HourlyEmployee object is dynamic as well?
Thanks!
Let me know if you guys want the rest of the code.
The way to do it is to put all Employee objects into a collection.
A good starting point is this tutorial.
Yes, you will be create several HourlyEmployee objects with the name "employee". As this question sounds a little homework-y, I won't give an example, but I will recommend that you investigate making an array of HourlyEmployee objects.
Try this,
Create an abstract class called Employee,
Then 2 concrete classes HourlyEmployee and SalaryEmployee.
Use ArrayList to store the employees, having same names wont create a clash, but Map would have been a better option where u can have Ids as unique keys to identify employees even though they have same names.
Eg:
public void addEmp(Employee employee){
ArrayList<? extends Employee> emp;
while(true){ // Use a boolean variable to terminate the loop at certain conditions
for (Employee e : emp) {
e.add(employee);
}
}
Consider this situation: I've got an aquarium simulator where I have 5 different types of fishes. Different types means different attributes (speed, colour, hunger, etc). What if I want the user of my simulator to be able to create a new type of fish and give it its values for its attributes?
How is that implemented by the programmer? Do I need some kind of "event handling" that will add a specific bunch of lines of code in my "Fish" class? Is that even a valid thought?
(In case it's essential, the language is Java. And to avoid any misunderstandings and prevent comments like "is this uni work?", yes it is. But I am not looking for THE answer, I am curious about the concept.)
EDIT: Yeah, my bad that I didn't mention the interaction way: a GUI.
So, imagine a tab called "Add New Species" that has a field for every attribute of the fishes (type, speed, colour, etc). So, the user fills in the fields with the appropriate values and when he clicks on "add" the constructor is called. At least that's how I imagine it. :)
I would just use a map:
class Fish
{
Map<String,String> attributes = new HashMap<String,String>();
setBusterFish()
{
attributes.put("speed", "5");
attributes.put("colour", "red");
attributes.put("hunger", "10");
attributes.put("name", "buster");
}
}
Java is an OO language, and it deals in classes and objects. The tempting, naive solution would be to have your program deal with "classes" of fish like it deals with classes of anything, i.e. to create some Java code and let the compiler and loader introduce it into the runtime.
This approach can be made to work, with some awkwardness. Essentially your "dynamic Java classes" coding would probably end up much bigger and complicated than your assignment actually intends.
You only really need to do this if you are actually going to have different attributes (not just different values of those attributes) for your different fish; and even then there are simpler solutions.
For what's being asked, I think you really only need one Fish class. When the user defines a new one, what he's really defining are the attribute values.
If you really want new and dynamic attributes, then you could go a long way using e.g. a HashMap to store name/value pairs. You could let the user add "legs" / "4" and then print out that new attribute as-is; but you couldn't make the fish walk on those legs because you'd be missing coding to work with the new attribute.
Have a look at the type object pattern. Also google for it I just gave one of the first references I found...
You may also look the Reflection pattern...
Let the user define attribute values of an instance of, say, a FishSpecies class, and give the FishSpecies a method createFish that creates a fish of that species (i.e. having those attribute values). Keeping track of all FishSpecies objects in a list grants you the opportunity to manage FishSpecies objects, and create Fish objects of given species.
If I understand your question correctly, then I believe that complicating things more than this is a mistake.