• Post Reply Bookmark Topic Watch Topic
  • New Topic

Collections API  RSS feed

 
Dar Var
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need some sort of collection to store unique keys and each key has a number of different values.

Is the best collection to use a Map?

i.e. a HashMap that stores each key as a String and the keys values as a String[]

I know that in a HashMap a key can only map to one value.
But is a String array the best approach to storing multiple values or would a Vector be better.

Or is there some other collection to use?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Dar Var:
...is a String array the best approach to storing multiple values or would a Vector be better.

Or is there some other collection to use?

I think you're on the right track with the Map (storing unique keys with their associated values). But depending on whether these multiple values could change in number, I might be more inclined to an ArrayList rather than a fixed-size array.

(Note: In new code, an ArrayList is generally preferred over a legacy Vector class.)
[ August 17, 2006: Message edited by: marc weber ]
 
Dar Var
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is an ArrayList more preferable than a Vector?

Does't the Vector class do the same but unlike ArrayList it is thread-safe.
 
Jeroen T Wenting
Ranch Hand
Posts: 1847
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vector is slow.
If you really need thread safety (usually you don't) there is a threadsafe version of ArrayList that's preferable to Vector.

In fact you should consider Vector to be deprecated, Sun just hasn't gotten around to mark it as such as it would require them to redo quite a few internal methods that use it in legacy code (mainly AWT and Swing).

What you're looking for is a structure like Map<Key, List<Value>> where Key and Value are what you want to store.
 
Dana Bothner-By
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also consider: are the values associated with a key *ordered*? Perhaps a Set would make more sense:

Map<Key, Set<Value>>
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!