• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can user define array variable?  RSS feed

 
Derek Smiths
Ranch Hand
Posts: 119
Eclipse IDE Mac VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Carey Brown
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
variable names are used by the programmer to keep track of stuff, not the end user.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!