Multi-valued hashtable in Java

前端 未结 13 2001
余生分开走
余生分开走 2020-12-06 09:41

Is it possible to have multiple values for the same key in a hash table? If not, can you suggest any such class or interface which could be used?

13条回答
  •  -上瘾入骨i
    2020-12-06 09:52

    As others pointed out, no. Instead, consider using a Multimap which can map many values for the same key.

    The Google Collections (update: Guava) library contains one implementation, and is probably your best bet.

    Edit: of course you can do as Eric suggests, and store a Collection as a value in your Hashtable (or Map, more generally), but that means writing unnecessary boilerplate code yourself. When using a library like Google Collections, it would take care of the low-level "plumbing" for you. Check out this nice example of how your code would be simplified by using Multimap instead of vanilla Java Collections classes.

提交回复
热议问题