我很好奇我如何更有效地實例化Java中的字典。目前我有可以通過的代碼,但我用非常混淆的方式填充數據。在Java中用一組特定的數據初始化字典
有什麼辦法讓我初始化我的字典嗎?這是蟒蛇的記錄:
westernCanadaAdjList = { 'BC': ['AB'],
'AB': ['BC', 'SK'],
'SK': ['AB', 'MB'],
'MB': ['SK']
}
我發現爲了演示的目的,這是一個更加清晰。
我當前的代碼在Java中:
public class Main {
public static void main(String[] args) {
//Adjacency List representation through a dictionary. Allows fast O(1) lookup time.
Map<String,ArrayList<String>> adjList = new HashMap<String,ArrayList<String>>();
//Adding values for Edmonton
adjList.put("Edmonton", new ArrayList<String>());
adjList.get("Edmonton").add("Neighbour1");
adjList.get("Edmonton").add("Neighbour2");
adjList.get("Edmonton").add("Neighbour3");
//Adding values for Vancouver
adjList.put("Vancouver", new ArrayList<String>());
adjList.get("Vancouver").add("V neighbour1");
adjList.get("Vancouver").add("V neighbour2");
System.out.println(adjList.keySet() +" And Values " + adjList.values());
for (String neighbour: adjList.get("Edmonton")){
System.out.println(neighbour);
}
for (String neighbour: adjList.get("Vancouver")){
System.out.println(neighbour);
}
}
}
非常感謝您!
也許在一個文本文件中將你的映射定義爲JSON,並用像Jackson這樣的解析器讀取它? – Riaz
不,Java沒有你希望的集合文字。 –