Java: can I have arrays in Hashmaps?
Can I 开发者_如何学Gohave arrays in Hashmaps ?
If so, what's the exact syntax to declare such hashmap ?
thanks
Arrays are objects, too. Even primitive arrays like int[]
.
Map<String,String[]> map = new HashMap<String,String[]>();
Value? that's fine, an array is an Object.
Key? Not so easy - see here:
Using a byte array as Map key
Yes. Below is an example that uses int [] as values. Example here.
Map<String, int[]> map = new TreeMap<String, int[]>();
HashMap<String, String[]> ab = new HashMap<String, String[]>();
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.
精彩评论