Meaningless Drivel is fun!
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "arrays - varied locations allowed?" Watch "arrays - varied locations allowed?" New topic

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.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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

Joined: Oct 02, 2003
Posts: 11955

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:
subject: arrays - varied locations allowed?
It's not a secret anymore!