JAVA为每个数组索引设置密钥

时间:2014-07-18 15:22:51

标签: java arrays

我是Java的新手,之前使用过PHP。我想在Java中定义一个数组,每个数组项都有一个键,就像在PHP中一样。例如,在PHP中我会这样:

$my_arr = array('one'=>1, 'two'=>2, 'three'=>3);

我如何用Java定义这个数组?

4 个答案:

答案 0 :(得分:3)

在Java中,数组索引始终为int类型。您要找的是Map。你可以这样做:

Map<String,Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);

答案 1 :(得分:2)

您需要的是Map实施,例如HashMap

请查看on this tutorialofficial Java tutorial了解更多详情。

答案 2 :(得分:2)

代码:

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

来源:如需阅读更多内容,请查看此来源

  1. http://java67.blogspot.com/2013/02/10-examples-of-hashmap-in-java-programming-tutorial.html
  2. Itrator教程

    2。http://www.java-samples.com/showtutorial.php?tutorialid=235

答案 3 :(得分:1)

对于使用Java的简单数组,你不能这样做,因为数组只是简单的容器。

值得庆幸的是,您可以使用的课程完全符合您的要求:

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

对于某些教程,请阅读:http://www.tutorialspoint.com/java/java_hashmap_class.htm

相关问题