Java:使用什么数据结构来模仿 PHP 的关联数组?
我想要一个允许我将键映射到值的数据结构,就像 PHP 的关联数组一样。每个键只能存在一次,但一个值可以映射到任意数量的键。我在寻找什么? Google Commons Collections 中有什么东西吗?
I want a data structure that allows me to map keys to values, like PHP's associative arrays. Each key can only exist once, but a value can be mapped to any number of keys. What am I looking for? Something in the Google Commons Collections?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
地图
结构就是你想要的。一个好的实现是HashMap
。此数据类型不允许 Key 具有相同的值,但您可以拥有任意数量的重复值。
用法示例:
换句话说,密钥只能存在一次。否则该值将被覆盖。
The
Map
structure is what you want. A good implementation is theHashMap
.This data type does not allow the same value for the Key, but you can have as many duplicate values as you like.
Example usage:
In other words, the key can only exist once. Otherwise the value is overwritten.
您正在寻找 HashMap,例如
HashMap< K,V>
。前者将对象映射到对象,后者映射您选择的类型(如其他泛型)。You're looking for a HashMap, such as a
HashMap<K,V>
. The former maps Objects to Objects, and the latter maps types of your choosing (like other generics).常规的 HashMap 有什么问题?如果您的值是字符串,您将免费获得引用计数,如果您需要引用对象的特定实例,则不要分配一个实例,而是使用现有引用
What's wrong with regular HashMap? If your values are Strings you'll get reference counting for free and if you need to refer to a particular instance of object just don't allocate one, but use existing reference
HashMap 是肯定的选择。事实上,当我第一次开始使用 PHP 编码时,我的看法是相反的。我想知道如何实现 HashMap?然后我发现了关联数组。
HashMap is the way to go for sure. I actually view things the other way around when I first started coding in PHP. I was wondering, how do I implement a HashMap? Then I discovered associative arrays.