Can Java use String as an index array key? (ex: array[“a”]=1;)

后端 未结 4 1750
夕颜
夕颜 2020-12-13 12:47

Can Java use a String as an index array key? Example:

array[\"a\"] = 1;
4条回答
  •  醉话见心
    2020-12-13 12:59

    No - you want a map to do that:

    Map map = new HashMap<>();
    map.put("a", 2);
    

    Then to get it:

    int val = map.get("a"); //2
    

    You can only use the square bracket syntax for arrays, not for any of the collections. So something like:

    int val = map["a"]; //Compile error
    

    Will always be illegal. You have to use the get() method.

提交回复
热议问题