I'm new to Java, coming from a C/C++ background. I'm trying to write a music player app for Android and I am working on a library scanning function. I want to have a hierarchical database of the format Artist -> Album -> Song where Artist has a name and a group of Albums, an Album has a name, year, and group of Songs, and a Song has a title, track number, and file location.
I created three classes to store this information:
public class libraryElementArtist
{
public String name;
public ArrayList<libraryElementAlbum> albums;
}
public class libraryElementAlbum
{
public String name;
public String year;
public ArrayList<libraryElementSong> songs;
}
public class libraryElementSong
{
public String name;
public int num;
public String filename;
}
The idea to fill them is simple - scan through each file and add its artist first, then album, then song. Each time it checks to make sure the artist/album does not already exist before creating a new one.
Essentially, I start off creating an ArrayList to store the artist information like this:
ArrayList<libraryElementArtist> libraryData = new ArrayList<libraryElementArtist>();
Then, to add an artist to the database:
libraryElementArtist newEntry = new libraryElementArtist();
newEntry.name = song_artist;
libraryData.add(newEntry);
And then to add an album:
libraryElementAlbum newEntry = new libraryElementAlbum();
newEntry.name = song_album;
libraryData.get(artistIndex).albums.add(newEntry);
where artistIndex is the index of the album's artist in the top-level artist array.
When I run this on the device and step through it in the debugger, the libraryElementArtist items are inserted into the libraryData array and their names are correctly filled in. However, the albums field is listed as null and trying to add albums does not fill in any data.
Sorry if this is a noob question, like I said I'm new to Java and I've searched and can't find what I'm looking for. Also, this is the way I'd do such a task in C++, not sure if it's the correct Java way.
I think is a Inheritance funda, So make your classes hierarchy as like (use of inheritance), So you have to make only one class which has all the derived propertied of its parent class, and make a ArrayList of that class only, So you don't have to make nested ArrayList. (If I am not wrong or if then please explain). :-)
Or generally make only one class which has all the properties, As you described above and use some getter,setter methods for that and using that class make your ArrayList.
create a custom class with getters and setters then create an arraylist as that datatype (your custom class)
List<customClass> foo = ArrayList<customClass>
same as the comment above but more info
All of the constructors should create (not just declare) the ArrayLists. Else they will be null. You can start them at a small size to save space. E.g
songs = new ArrayList(3);
Related
I have a class for creating basic grocery store items (class storeItems). I want to allow the user to make their own grocery store item by creating a new class object based on parameters that I receive from the user; i.e: "What is the name?" "What is the price?" "How much in stock?" etc. I also do not want to define the number of objects that can be created, so that it can be expanded as needed by the user.
Everything is properly structured, other than the object variable names themselves.
How would I go about creating these objects? Most of my Googling has suggested to use maps, but I can't for the life of me figure out how I would structure this.
This is essentially what I am trying to do:
public static Map<String,storeItems> storeItemMapper = new HashMap<String,storeItems>();
public static void itemBuilder(String mapObjName, String itemName, double price, int initialQuantity) {
storeItems object[i] = new storeItems(itemName, price, initialQuantity);
storeItemMapper.put(mapObjName, object[i]);
}
You are wrongly indexing the variable declaration:
storeItems object[i] = new storeItems(itemName, price, initialQuantity);
Try:
storeItems object = new storeItems(itemName, price, initialQuantity);
Without the index [i]. And as I said in the commentary, you should to use the CamelCase standard to name classes:
StoreItems object = new StoreItems(itemName, price, initialQuantity);
I am relatively new to Java. I have been struggling to define a class that meets my needs. Searching on this site or google did not have probably because the question is so specific. Any help is appreciated!
Ideally the class (lets call it Filer) would have:
Name (string)
Volumes (Collection/list of Strings: 0 -100)
Each Volume, in turn, will have:
A. Name (string)
B. Servers_Permed (another collection/list of Strings: 0-40)
Once I can get the class defined, I will do ok with defining getters and setters to use it, but so far I have failed to defined the class without getting totally lost :-)
Thanks!
It seams that your description is not correct.
You need a class Filer with:
name (String)
volumes (list of Volume) (not strings as you asked, because you explained differently on the second part of the question, it is evident that you need a list of Volume and not a list of String)
And a second class Volume with:
Name (string)
Servers_Permed (list of strings)
So you need a data structure like the following:
public class Volume {
private String name;
private List<String> serversPermed; // Changed the name to a name more adherent to standard guidelines
...
}
public class Filer {
private String name;
private List<Volume> volumes;
...
}
well, lay it out piece by piece.
First, you have Volume (not sure how volumes could be "Collection/list of Strings: 0 -100" and have the following properties):
public class Volume {
String name;
List<String> servers_permed;
}
Now you have Filer:
public class Filer {
String name;
List<Volume> volumes;
}
you will have to add the necessary constructors, getters/setters.
Both of the answer given above worked beautifully (they are almost the same anyway).
Thank you, Davide and DBug!
I'm a java beginner and have a question concerning how to best structure a cooking program.
I have a class called Ingredient, this class currently looks like this:
public class Ingredient {
private String identifier;
private double ingredientFactor;
private String titleInterface;
public Ingredient(String identifier, double ingredientFactor,String titleInterface) {
this.identifier = identifier;
this.ingredientFactor = ingredientFactor;
this.titleInterface = titleInterface;
}
I want to initialize several objects (about 40) with certain values as instance variables and save them in a Map, for example
Map<String, Ingredient> allIngredients = new HashMap<String, Ingredient>();
allIngredients.put("Almonds (ground)", new Ingredient("Almonds (ground)", 0.7185, "Almonds (ground)");
Later on I want to retrieve all these objects in the form of a Map/HashMap in a different class.
I'm not sure how to proceed best, initialize all these objects in the Ingredient class itself or provide a method that initializes it or would it be better to create an super class (AllIngredients or something like that?) that has a Map with Ingredients as instance variables?
Happy for any suggestions, thanks in advance :)
Please do not initialize all these objects in the Ingredient class itself. That would be a bad practice for oops.
Just think your class is a template from which you create copies(objects) with different values for attributes. In real world if your class represent model for a toy plane which you would use to create multiple toy planes but each bearing different name and color then think how such a system would be designed. You will have a model(class). Then a system(another class) for getting required color and name from different selection of colors and names present(like in database,files,property file ) etc.
Regarding your situation .
If predetermined values store the values in a text file,properties file,database,constants in class etc depending on the sensitivity of the data.
Create Ingredient class with constructors
Create a class which will have methods to initialize Ingredient class using predetermined values,update the values if required,save the values to text file -database etc and in your case return as map .
Also check the links below
http://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm
http://www.oracle.com/technetwork/java/dataaccessobject-138824.html
Sounds to me like you are looking for a static Map.
public class Ingredient {
private String identifier;
private double ingredientFactor;
private String titleInterface;
public Ingredient(String identifier, double ingredientFactor, String titleInterface) {
this.identifier = identifier;
this.ingredientFactor = ingredientFactor;
this.titleInterface = titleInterface;
}
static Map<String, Ingredient> allIngredients = new HashMap<String, Ingredient>();
static {
// Build my main set.
allIngredients.put("Almonds (ground)", new Ingredient("Almonds (ground)", 0.7185, "Almonds (ground)"));
}
}
I'm trying to make an array of objects called Verbs.
The Verb class has 4 Strings.
public class Verb {
String maori;
String englishPast;
String englishPresent;
String englishFuture;
}
Do I need to write get and set methods into this class in order to change these values or does android handle it for you somehow?
This seems to not be an Android problem but a java related question. You should create a Verb class like this:
public class Verb {
private String maori;
//All other strings you need
public String getMaori() {
return maori;
}
//Add a setter as well
Then you should create your Verb objects and add these objects to your array. But this has nothing to do with Android at all!
How can I do such a thing?
String N = jTextField0.getText();
MyClass (N) = new Myclass();
Is it even possibe?
Or as my question's explains, how can I just make a method to create a new object of my specified class just with a different name each time I call it.
I really searched everywhere with no luck.
Thanks in Advance
P.S.
I wish you guys can excuse me for not being clear enough, Just to say it as it is, I made a textfield to get the name of someone who wants to make an account, and I made a class named "Customer". and a button named "Add". Now I want every time "Add" is clicked, compiler take what is in my textfield and make an object of the class "Customer" named with what it took from the textfield
It was too hard to read it in comments so I updated my question again, so sorry.
I'm stuck so bad. I suppose my problem is that I didn't "understand" what you did and only tried to copy it. This is what I wrote:
private void AddB0MouseClicked(java.awt.event.MouseEvent evt) {
String name = NameT0.getText();
Customer instance = new Customer(Name);
Customer.customers.add(instance);
and this is my Customer class:
public class Customer{
String name;
public Customer(String name){
this.name = name;
}
public String getName(){
return name;
}
static ArrayList<Customer> customers = new ArrayList<Customer>();
Variable names must be determined at compile time, they are not even part of the generated code. So there is no way to do that.
If you want to be able to give your objects names, you can use
Map<String, MyClass> map = new HashMap<>();
Add objects to the map like this (e.g):
map.put(userInput, new MyClass());
and retrieve objects like this:
MyClass mc = map.get(userInput);
I'm not entirely sure what you mean by...
how can I just make a method to create a new object of my specified
class just with a different name each time I call it
...but if I'm interpreting you correctly, I believe what you're trying to do as make MyClass accept a constructor parameter. You can do:
public class MyClass {
private String name;
public MyClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then to create a new instance of MyClass, do:
String name = jTextField0.getText();
MyClass instance = new MyClass(name);
instance.getName(); // returns the name it was given
EDIT
Since you've added clarifications in the comments since I first answered this question, I thought I would update the answer to portray more of the functionality that you're looking for.
To keep track of the MyClass instances, you can add them to an ArrayList. ArrayList objects can be instantiated as follows:
ArrayList<MyClass> customers = new ArrayList<MyClass>();
Then for each MyClass instance you wish to add, do the following:
customers.add(instance);
Note that the ArrayList should not be reinstantiated for each instance that you wish to add; you should only instantiate the ArrayList once.