Java HashMap
Java HashMap
在 ArrayList
章中,你瞭解到陣列將專案儲存為有序集合,並且你必須使用索引號(int
型別)來訪問它們。而 HashMap
則以“鍵/值”對的形式儲存專案,你可以透過另一種型別的索引(例如 String
)來訪問它們。
一個物件被用作另一個物件(值)的鍵(索引)。它可以儲存不同的型別:String
鍵和 Integer
值,或者相同的型別,例如:String
鍵和 String
值。
示例
建立一個名為 capitalCities 的 HashMap
物件,它將儲存 String
鍵和 String
值。
import java.util.HashMap; // import the HashMap class
HashMap<String, String> capitalCities = new HashMap<String, String>();
Add Items
HashMap
類有許多有用的方法。例如,要向其中新增專案,請使用 put()
方法。
示例
// Import the HashMap class
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Create a HashMap object called capitalCities
HashMap<String, String> capitalCities = new HashMap<String, String>();
// Add keys and values (Country, City)
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities);
}
}
訪問專案
要訪問 HashMap
中的值,請使用 get()
方法並引用其鍵。
Remove an Item
要刪除一個專案,請使用 remove()
方法並引用該鍵。
要刪除所有專案,請使用 clear()
方法。
HashMap 大小
要找出有多少專案,請使用 size()
方法。
遍歷 HashMap
使用 for-each 迴圈遍歷 HashMap
中的專案。
注意:如果只想獲取鍵,請使用 keySet()
方法;如果只想獲取值,請使用 values()
方法。
示例
// Print keys and values
for (String i : capitalCities.keySet()) {
System.out.println("key: " + i + " value: " + capitalCities.get(i));
}
Other Types
HashMap 中的鍵和值實際上都是物件。在上面的示例中,我們使用了“String”型別的物件。請記住,Java 中的 String 是一個物件(而不是基本型別)。要使用其他型別,例如 int,您必須指定一個等效的包裝類:Integer
。對於其他基本型別,請使用:boolean 的 Boolean
,char 的 Character
,double 的 Double
等。
示例
建立一個名為 people 的 HashMap
物件,它將儲存 String
鍵和 Integer
值。
// Import the HashMap class
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Create a HashMap object called people
HashMap<String, Integer> people = new HashMap<String, Integer>();
// Add keys and values (Name, Age)
people.put("John", 32);
people.put("Steve", 30);
people.put("Angie", 33);
for (String i : people.keySet()) {
System.out.println("key: " + i + " value: " + people.get(i));
}
}
}
完整的 HashMap 參考手冊
有關 HashMap 方法的完整參考,請訪問我們的Java HashMap 參考手冊。