HashMap
- 可以有N個Key與Value,但一個map只會有一個key存在
- 型態可以根據初始化來決定
- 不會按順序排序
Map<String, Integer> map1 = new HashMap<>();
map1.put("k123", 0);
map1.put("k123", 0);
map1.put("f345", 1);
map1.put("a234", 2);
map1.put("b234", 4);
map1.put("c234", 3);
System.out.println();
for(String map: map1.keySet()) {
System.out.print(map + ", ");
}
//資料沒按照put的順序排列
//打印f345, k123, b234, c234, a234,
//Location為class
private Map<Integer, Location> locations = new HashMap<>();
public static void main(String[] args) {
Map<String, Integer> tempExit = new HashMap<>();
//新增map,
locations.put(0, new Location(0,"data1", tempExit));
//避免曝露,如下刪除後,如果曝露,變更參數後,則會影響內部資料
tempExit.remove("S");
}
//Location
//this.map = map; 如果這樣的話,外部數值變化,內部也會跟著變化
//避免曝露,內部需要改成這樣,外部數值變化,內部並不會改變
if(map != null) {
this.map = new HashMap<>(map);
} else {
this.map = new HashMap<>();
}
可以使用以下方式找到對應的key,以及讀取
//map -> Map<String, Integer> map;
if(map.containsKey("key1")) {
//找到此key
int data = map.get("key1")
}
遍歷Map
for(String map: mpas.keySet()) {
System.out.print(map + ", ");
}
for(Map.Entry<String, Integer> map: exits.entrySet()) {
System.out.println("key: " + map.getKey() +
", value: " + map.getValue());
}
Collections.unmodifiableMap禁止修改Map
可以利用return,限制是否禁止修改Map
public Map<String, Integer> getMap() {
return Collections.unmodifiableMap(exits);
}