【发布时间】:2026-01-04 20:20:07
【问题描述】:
我是 Java 新手,之前使用过 PHP。我想在 Java 中定义一个数组,其中每个数组条目都有一个键,就像在 PHP 中一样。例如,在 PHP 中我会这样:
$my_arr = array('one'=>1, 'two'=>2, 'three'=>3);
如何在 Java 中定义这个数组?
【问题讨论】:
-
您可能需要使用 java.util.Map
我是 Java 新手,之前使用过 PHP。我想在 Java 中定义一个数组,其中每个数组条目都有一个键,就像在 PHP 中一样。例如,在 PHP 中我会这样:
$my_arr = array('one'=>1, 'two'=>2, 'three'=>3);
如何在 Java 中定义这个数组?
【问题讨论】:
在 Java 中,数组索引的类型总是int。您正在寻找的是Map。你可以这样做:
Map<String,Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
【讨论】:
代码:
import java.util.*;
public class HashMapExample
{
public static void main (String[] args)
{
Map<String,Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
//how to traverse a map with Iterator
Iterator<String> keySetIterator = map.keySet().iterator();
while(keySetIterator.hasNext()){
String key = keySetIterator.next();
System.out.println("key: " + key + " value: " + map.get(key));
}
}
}
输出:
key: one value: 1
key: two value: 2
key: three value: 3
来源:要阅读更多内容,请查看此来源
迭代器教程
2.http://www.java-samples.com/showtutorial.php?tutorialid=235
【讨论】:
.iterator() 和 keySetIterator.next() 是什么 HashMap
您需要的是Map 实现,例如HashMap。
查看on this tutorial 或official Java tutorial 了解更多详情。
【讨论】:
你不能在 Java 中使用简单的数组来做到这一点,因为数组只是简单的容器。
谢天谢地,您可以使用一个完全符合您要求的类:
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
有关一些教程,请阅读:http://www.tutorialspoint.com/java/java_hashmap_class.htm
【讨论】: