更新時(shí)間:2021-10-22 10:32:47 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽1015次
數(shù)組將項(xiàng)目存儲(chǔ)在有序集合中,并使用索引號(hào)(這是一個(gè)整數(shù))進(jìn)行訪問(wèn)。HashMap將項(xiàng)目存儲(chǔ)為鍵/值對(duì)。值可以通過(guò)用戶(hù)定義類(lèi)型的索引(稱(chēng)為鍵)訪問(wèn)。Java HashMap 類(lèi)通過(guò)使用哈希表1來(lái)實(shí)現(xiàn)映射接口。
Java 映射是使用關(guān)鍵字 聲明的Map。后面是<>包含鍵和值數(shù)據(jù)類(lèi)型的尖括號(hào)。第一個(gè)參數(shù)是鍵的數(shù)據(jù)類(lèi)型,第二個(gè)參數(shù)是映射值的數(shù)據(jù)類(lèi)型。后面跟著地圖的名字。
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類(lèi)中一些有用的方法:
添加項(xiàng): 該put()方法用于在 HashMap 中添加新的鍵/值對(duì)或替換現(xiàn)有鍵的值。第一個(gè)參數(shù)是鍵,第二個(gè)參數(shù)是映射值。
shapes.put(6,"hexagon")
訪問(wèn)一個(gè)項(xiàng)目: 該get()方法將一個(gè)鍵作為輸入來(lái)訪問(wèn)它在 HashMap 中的關(guān)聯(lián)值。
shapes.get(3)
刪除所有項(xiàng): 該clear()方法用于刪除HashMap中的所有元素。
shapes.clear()
刪除項(xiàng): 該remove()方法將特定鍵作為輸入并刪除其在 HashMap 中的關(guān)聯(lián)值。
shapes.remove(1)
Check if HashMap is empty: 該isEmpty()方法是檢查map是否為空。如果地圖為空,則返回 true,否則返回 false。
shapes.isEmpty()
HashMap 的大?。?該size()方法用于查找 HashMap 中鍵/值對(duì)的數(shù)量。
shapes.size()
下面是一個(gè) HashMap 的 Java 代碼實(shí)現(xiàn):
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基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問(wèn)老師會(huì)電話與您溝通安排學(xué)習(xí)