具有非数字键的 PHP 数组的 Java 等效项是什么?

发布于 2024-10-07 16:16:21 字数 238 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

北音执念 2024-10-14 16:16:21

您可以使用 HashMap 或 < a href="http://download.oracle.com/javase/6/docs/api/java/util/Hashtable.html" rel="nofollow noreferrer">哈希表。不确定该使用哪一个?阅读 API 或查看此问题,其中讨论了每种 API 的优缺点。

HashMap<String, String> map = new HashMap<String, String>();
map.put("name", "John");
map.put("email", "[email protected]");

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.

HashMap<String, String> map = new HashMap<String, String>();
map.put("name", "John");
map.put("email", "[email protected]");
携余温的黄昏 2024-10-14 16:16:21

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.

流绪微梦 2024-10-14 16:16:21

请记住,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.

浪漫人生路 2024-10-14 16:16:21

我建议你使用LinkedHashMap。它相对于 HashMap 的主要优点是它保留了键的添加顺序。对于 HashMap,它们以伪随机顺序出现,这使得读取它们变得更加困难。

Map<String, String> map = new LinkedHashMap<String, String>();
map.put("name", "John");
map.put("email", "[email protected]");

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.

Map<String, String> map = new LinkedHashMap<String, String>();
map.put("name", "John");
map.put("email", "[email protected]");
泪意 2024-10-14 16:16:21

它叫做 java.util.HashMap

It's called java.util.HashMap

怪我闹别瞎闹 2024-10-14 16:16:21
Map user = new HashMap();
user.put("name", "John");
user.put("email", "[email protected]");
Map user = new HashMap();
user.put("name", "John");
user.put("email", "[email protected]");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文