具有非数字键的 PHP 数组的 Java 等效项是什么?
Java 中 php 数组的等价物是这样的:
$user = array("name" => "John", "email" => "[email protected]");
What would be Java equivalent for php array like this:
$user = array("name" => "John", "email" => "[email protected]");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用 HashMap 或 < a href="http://download.oracle.com/javase/6/docs/api/java/util/Hashtable.html" rel="nofollow noreferrer">哈希表。不确定该使用哪一个?阅读 API 或查看此问题,其中讨论了每种 API 的优缺点。
You can use a HashMap or a Hashtable. Not sure which one to use? Read the API or check out this question which discusses the pros and cons of each.
Map 接口的实现在 Java 中相当于关联数组,但看起来您真正想要的是带有姓名和电子邮件字段的 User 类。
An implementation of the Map interface is the Java equivalent of an associative array, but it seems like what you really want is a User class with fields for name and email.
请记住,PHP 的关联数组会跟踪它们的插入顺序。因此,如果您使用
foreach
迭代它们的键,您将以相同的顺序获得它们。最接近的 Java 等效项可能是 LinkedHashMap 。
Keep in mind that PHP's associative arrays keep track of the order they were inserted. So if you use
foreach
to iterate over their keys, you'll get them in the same order.The closest Java equivalent is probably LinkedHashMap.
我建议你使用LinkedHashMap。它相对于 HashMap 的主要优点是它保留了键的添加顺序。对于 HashMap,它们以伪随机顺序出现,这使得读取它们变得更加困难。
I would suggest you use LinkedHashMap. Its main advantage over HashMap its that it retains the order the keys were added. For HashMap they appear in a pseudo random order which makes reading them much harder.
它叫做 java.util.HashMap
It's called java.util.HashMap
尝试 http://download.oracle.com/ javase/1.4.2/docs/api/java/util/Map.html,或更具体地说 http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html。
Try http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html, or more specifically a http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html.