更新時間:2021-10-22 10:32:47 來源:動力節點 瀏覽1042次
數組將項目存儲在有序集合中,并使用索引號(這是一個整數)進行訪問。HashMap將項目存儲為鍵/值對。值可以通過用戶定義類型的索引(稱為鍵)訪問。Java HashMap 類通過使用哈希表1來實現映射接口。
Java 映射是使用關鍵字 聲明的Map。后面是<>包含鍵和值數據類型的尖括號。第一個參數是鍵的數據類型,第二個參數是映射值的數據類型。后面跟著地圖的名字。
import java.util.HashMap; // import HashMap class
import java.util.Map; // import Map Interface
class MyClass {
public static void main( String args[] ) {
HashMap<Integer, String> shapes = new HashMap<Integer,String>(); // Create an ArrayList object with string data type
}
}
下面是HashMap類中一些有用的方法:
添加項: 該put()方法用于在 HashMap 中添加新的鍵/值對或替換現有鍵的值。第一個參數是鍵,第二個參數是映射值。
shapes.put(6,"hexagon")
訪問一個項目: 該get()方法將一個鍵作為輸入來訪問它在 HashMap 中的關聯值。
shapes.get(3)
刪除所有項: 該clear()方法用于刪除HashMap中的所有元素。
shapes.clear()
刪除項: 該remove()方法將特定鍵作為輸入并刪除其在 HashMap 中的關聯值。
shapes.remove(1)
Check if HashMap is empty: 該isEmpty()方法是檢查map是否為空。如果地圖為空,則返回 true,否則返回 false。
shapes.isEmpty()
HashMap 的大小: 該size()方法用于查找 HashMap 中鍵/值對的數量。
shapes.size()
下面是一個 HashMap 的 Java 代碼實現:
import java.util.HashMap; //importing the HashMap class
import java.util.Map; // importing the Map interface
class MyClass {
public static void main( String args[] ) {
HashMap<Integer,String> shapes = new HashMap<Integer,String>(); //create a HashMap with Integer keys and String Values
shapes.put(4,"square"); // add square at key 4
shapes.put(3,"triangle"); // add triangle at key 3
shapes.put(6,"hexagon"); // add hexagon at key 6
shapes.put(8,"octagon"); // add octagon at key 8
shapes.put(5,"pentagon"); // add pentagon at key 5
System.out.println(shapes); // print keys and mapped values
shapes.remove(3); // removing value at key 3
shapes.remove(5); // removing value at key 5
System.out.println("Updated map:");
System.out.println(shapes); // prints keys and mapped values
shapes.put(4,"rhombus"); // replaces value at key 4 with rhombus
System.out.println("Updated map:");
System.out.println(shapes); // prints keys and mapped values
System.out.println("Size of map is "+shapes.size());
shapes.clear(); // removes all key/value pairs in the HashMap
System.out.println("Updated map:");
System.out.println(shapes); // prints keys and mapped values
}
}
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習