-2

I have defined clusters variable as shown below in java.

HashMap<double[],String> clusters = new HashMap<double[],String>();

My question is how can I access String values one by one from clusters? Ex. String name=clusters."?";

Basilevs
  • 22,440
  • 15
  • 57
  • 102
  • 2
    possible duplicate of [Iterate over each Entry in a Map](http://stackoverflow.com/questions/46898/iterate-over-each-entry-in-a-map) – holgac Apr 04 '15 at 10:54
  • @holgac, find a question with iteration over values. The one you propose asks about entries. – Basilevs Apr 04 '15 at 11:28
  • 1
    possible duplicate of [How to get values. keys from HashMap?](http://stackoverflow.com/questions/16246821/how-to-get-values-keys-from-hashmap) – Joe Apr 04 '15 at 11:37

2 Answers2

3

This is a really bad idea to use arrays as keys in HashMap, because hashCode() of array can return different values for array instances with the same content.

skozlov
  • 384
  • 1
  • 12
  • Then what is the solution if I want to use same arguments?? And access Strings one by one? – user3553419 Apr 04 '15 at 10:57
  • @skozlov This is true, but I don't think it is necessarily relevant to the issue described - irrespective of changes to the hash code due to post-insertion changes, it is still possible to retrieve all of the values using `clusters.values()`. – Andy Turner Apr 04 '15 at 10:58
  • Yes I know that. But I want to access Strings one by one. Not all at a time as set. Then? – user3553419 Apr 04 '15 at 11:00
  • @user3553419, see answer below – skozlov Apr 04 '15 at 11:00
0

You can iterate the values using Map.values():

for (String value : clusters.values()) {
  // ... whatever.
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243