公告
财富商城
积分规则
提问
发文
2019-01-22 01:06发布
看我几分像从前
Can Java use a String as an index array key? Example:
array["a"] = 1;
No they can't. But they can use chars the ASCII value of the alphabet will be used as the key index
Consider
String[] a = new String['a' + 1]; a['a'] = "Hello"; int[] b = new int['a' + 3]; b['c'] = 5; System.out.println(a[97]); System.out.print(b[99]);
This will output
Hello 5
No.
To do something like this, you have to use a Map.
Map<String, Integer> aMap = new HashMap<String, Integer>(); aMap.put("a" , Integer.valueOf(1));
No - you want a map to do that:
Map<String, Integer> 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.
get()
No, that would be a Map in Java.
(The type would be Map<String,Integer>.)
Map<String,Integer>
最多设置5个标签!
No they can't. But they can use chars the ASCII value of the alphabet will be used as the key index
Consider
This will output
No.
To do something like this, you have to use a Map.
No - you want a map to do that:
Then to get it:
You can only use the square bracket syntax for arrays, not for any of the collections. So something like:
Will always be illegal. You have to use the
get()
method.No, that would be a Map in Java.
(The type would be
Map<String,Integer>
.)