修改 Java HashMap 中與給定鍵關聯的值


首先,建立一個 HashMap 並向其中新增元素 −

// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Frames", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));

現在,要修改與給定鍵關聯的值,請使用 put() 方法。這裡,我們正在修改鍵 “Frames“ 的值 −

hm.put("Frames", "900");

以下是修改與給定鍵關聯的值的一個示例 −

示例

 線上演示

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Bag", new Integer(1100));
      hm.put("Sunglasses", new Integer(2000));
      hm.put("Frames", new Integer(800));
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      // Get a set of the entries
      Set set = hm.entrySet();
      System.out.println("Elements in HashMap...");
      System.out.println(set);
      hm.put("Frames", "900");
      System.out.println("
Updated HashMap Elements..."); System.out.println(hm); } }

輸出

Elements in HashMap...
[Frames=800, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000]

Updated HashMap Elements...
{Frames=900, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000}

更新日期: 2019 年 7 月 30 日

248 次觀看

啟動你的 職業生涯

完成課程認證

開始
廣告