首页 课程 师资 教程 报名

HashMap用法示例

  • 2021-10-22 10:23:17
  • 670次 星辉

HashMap 是一个基于 Map 的集合类,用于存储 Key & value 对,表示为 HashMap<Key, Value>  或 HashMap<K, V>。此类不保证地图的顺序。它类似于 Hashtable 类,除了它是不同步的并且允许空值(空值和空键)。

它不是一个有序集合,这意味着它不会以它们插入 HashMap 的相同顺序返回键和值。它不会对存储的键和值进行排序。您必须需要导入java.util.HashMap或其超类才能使用 HashMap 类和方法。

Java 中的 HashMap 示例:

在这个例子中,我们已经演示了 HashMap 类的几乎所有重要方法。

import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Details {
   public static void main(String args[]) {
      /* This is how to declare HashMap */
      HashMap<Integer, String> hmap = new HashMap<Integer, String>();
      /*Adding elements to HashMap*/
      hmap.put(12, "Chaitanya");
      hmap.put(2, "Rahul");
      hmap.put(7, "Singh");
      hmap.put(49, "Ajeet");
      hmap.put(3, "Anuj");
      /* Display content using Iterator*/
      Set set = hmap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry mentry = (Map.Entry)iterator.next();
         System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
         System.out.println(mentry.getValue());
      }
      /* Get values based on key*/
      String var= hmap.get(2);
      System.out.println("Value at index 2 is: "+var);
      /* Remove values based on key*/
      hmap.remove(3);
      System.out.println("Map key and values after removal:");
      Set set2 = hmap.entrySet();
      Iterator iterator2 = set2.iterator();
      while(iterator2.hasNext()) {
          Map.Entry mentry2 = (Map.Entry)iterator2.next();
          System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
          System.out.println(mentry2.getValue());
       }
   }
}

输出:

key is: 49 & Value is: Ajeet
key is: 2 & Value is: Rahul
key is: 3 & Value is: Anuj
key is: 7 & Value is: Singh
key is: 12 & Value is: Chaitanya
Value at index 2 is: Rahul
Map key and values after removal:
Key is: 49 & Value is: Ajeet
Key is: 2 & Value is: Rahul
Key is: 7 & Value is: Singh
Key is: 12 & Value is: Chaitanya

如果您想了解更多关于HashMap的知识,不妨来关注一下星辉的Java基础教程,里面有更多相关内容可以学习,课程通俗易懂,适合小白,希望对大家能够有所帮助。

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交