Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes arrays - varied locations allowed? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "arrays - varied locations allowed?" Watch "arrays - varied locations allowed?" New topic
Author

arrays - varied locations allowed?

Matt Fielder
Ranch Hand

Joined: Oct 27, 2004
Posts: 158
I want to create several arrays to hold different pieces of data. The data will be number related and it would be convenient to make each number in the array be appropriate to the string held there.

for instance
month[1] = "January"
month[2] = "February"

*assume I don't need these months*

month[10] = "October"
month[11] = "November"

Can I just omit 3 - 9 in the array or do the numbers have to be sequential?

Thanks for any help.
Matt
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Array indices have to be sequential, but you don't necessarily have to use arrays. You could use a Map to associate numbers (or Strings or anything) with Strings (or numbers or anything else.)



The keys and values in a Map can be any Java objects. The only complication is that you have to cast the result of the "get" operation to the correct type -- unless you're using generics in Tiger.


[Jess in Action][AskingGoodQuestions]
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11153
    
  16

While the numbers in the array are sequential, you don't have to use them all. It is perfectly valid to only assign objects to the four indicies you list.

But, Ernest is right (as usual) in that an Array might not be the best way to do this.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Matt Fielder
Ranch Hand

Joined: Oct 27, 2004
Posts: 158
So, instead of

month[1] = "January"

I could use

month[jan] = "January"

??
I think the answer is yes. It is just a variable naming that location in the array. Am I wrong?
[ April 13, 2005: Message edited by: Matt Fielder ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: arrays - varied locations allowed?
 
Similar Threads
An object to hold several arrays
Doubt about Array length ..
array of arrays with arraylist
Checking for unique values in an array
Enumerable.Range() in Java?