首页 课程 师资 教程 报名

HashMap是什么

  • 2021-10-22 10:32:47
  • 726次 星辉

数组将项目存储在有序集合中,并使用索引号(这是一个整数)进行访问。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 中的有用方法

下面是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 实现

下面是一个 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    
  }
}

 

选你想看

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

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

先测评确定适合在学习

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