2

Can I have arrays in Hashmaps ?

If so, what's the exact syntax to declare such hashmap ?

thanks

user680406
  • 5,637
  • 6
  • 24
  • 19

5 Answers5

5

Arrays are objects, too. Even primitive arrays like int[].

Map<String,String[]> map = new HashMap<String,String[]>();
Jeremy
  • 22,188
  • 4
  • 68
  • 81
  • Uhm, what about this: HashMap[]> ? I get an error. I have an array with Lists inside. – user680406 Mar 31 '11 at 16:55
  • 2
    I don't get an error from `Map[]> map = new LinkedHashMap[]>();` – Peter Lawrey Mar 31 '11 at 16:57
  • 3
    @user680406 I think you'll need to clarify what you're trying to do. Are you confusing arrays and ArrayLists? In your example (that you said didn't work) you are creating a Map where each value in the map is an array of Lists of Strings i.e. each String key maps to an array and each element of that array is a List and each element of that List is a String! Is that right? I'm thinking maybe you've gone one step too far and what you want is either HashMap> or HashMap - is that right? – CodeClimber Mar 31 '11 at 17:03
  • 1
    @user680406: I'm guessing you actually want `HashMap>`. It would be silly to have an array of `ArrayLists`. – Jonah Mar 31 '11 at 17:13
2

Value? that's fine, an array is an Object.

Key? Not so easy - see here:

Using a byte array as Map key

Community
  • 1
  • 1
CodeClimber
  • 4,584
  • 8
  • 46
  • 55
1

Yes. Below is an example that uses int [] as values. Example here.

Map<String, int[]> map = new TreeMap<String, int[]>();
Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
0

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

James.Xu
  • 8,249
  • 5
  • 25
  • 36
0

I think you should use ArrayList instead of a primitive array. Becouse of the == comparision done inside of the HashMap class.

So, you could have something like this:

HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();

When the map checks if some element (given its key "k") is present in the array it computes its hashcode. If there's some element at that position "k", then a colision may be produced, so it checks if the elements are the same. Something that can have some troubles with primitives arrays.

santiagobasulto
  • 11,320
  • 11
  • 64
  • 88