Forums Register Login

Can user define array variable?

+Pie Number of slices to send: Send
I am writing a program to store books (Book class) in volumes (Volume class). Within the main class (DemoVolume) I am doing a couple different things. I want to ask the user if they are creating a new array, if yes, I was to create a new array with a variable names assigned by the user. Is this possible? The reason is I want to allow the user to be able to search their library of volumes. If no, then the user will enter the book information and I will assign it to an array unassignedVolume that will contain individual books. I would also like to create book objects that are defined with the book name, if this is possible. I'm just messing around and trying to deepen my understanding of JAVA. My main issue is how to allow the user to title the volume (array variable).
+Pie Number of slices to send: Send
No, you can't name an array dynamically, however you can have a Map (e.g. HashMap) that associates a key with a collection. Example
HashMap<String,ArrayList<MyClass>>
Where String is the volume title. ArrayList is used in place of an array and can be dynamically sized.
+Pie Number of slices to send: Send
variable names are used by the programmer to keep track of stuff, not the end user.
+Pie Number of slices to send: Send
 

Carey Brown wrote:... you can have a Map (e.g. HashMap) that associates a key with a collection. Example
HashMap<String,ArrayList<MyClass>>
Where String is the volume title. ArrayList is used in place of an array and can be dynamically sized.


A few clarifications:

Maps associate Keys with Values.

It's up to you to specify the type of the Key and the type of the associated Value when you declare your variable. What makes sense in this case, if I understand what the OP wants to do correctly, would be a Map<String, List<Book>>. Map and List are interfaces. Prefer to declare types using interfaces rather than concrete implementation types, e.g. HashMap and ArrayList. Like so:

See http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html for more about the diamond operator
Make yourself as serene as a flower, as a tree. And on wednesdays, as serene as this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 568 times.
Similar Threads
Why is my type unexpected? required variable found value
i don't know which way i should use?
ArrayList - Contact Information/Address Book
Calling a method from another class
The method is undefined for the type
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 09:40:13.