JAVA 中 PHP 关联数组的替代方案
在 PHP 中,我可以使用以字符串作为键的数组。例如 $some_array["猫"] = 123; $some_array["狗"] = 456; 我刚刚切换到 Java,但找不到能够执行此操作的数据结构。这可能吗?
In PHP I could use an array with strings as keys. eg
$some_array["cat"] = 123;
$some_array["dog"] = 456;
I just switched to Java and I can't find a data structure capable of doing this. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您所描述的是一个关联数组,也称为表,字典,或者地图。
在 Java 中,您需要
Map
接口,并且可能需要HashMap
类作为实现。What you are describing is an associative array, also called a table, dictionary, or map.
In Java, you want the
Map
interface, and probably theHashMap
class as the implementation.您可以使用 Map 实现之一,例如作为 HashMap 来做到这一点。
You would use one of the Map implementations such as HashMap to do that.
您想要使用
Map
,很可能是HashMap< /代码>
。
You want to use a
Map
, most likely aHashMap
.您需要的数据结构是
Map
。我相信它是一个抽象类,因此您必须使用它的具体子类之一,例如HashMap
The data structure you are after is
Map
. I believe its an abstract class so you'll have to use one of its concrete subclasses likeHashMap<?>
正如很多人所说,地图就是您要寻找的东西。如果这是您的选择,请不要忘记重新实现 hashcode() 和 equals()。看一下,因为这是必须的: http://www.ibm .com/developerworks/java/library/j-jtp05273/index.html
As many people said, a Map is what you are looking for. If that was your choice, do not forget to reimplement hashcode() and equals(). Take a look because is a must: http://www.ibm.com/developerworks/java/library/j-jtp05273/index.html