10.21-hashmap-2

创建一个 HashMap 对象 Sites, 整型(Integer)的 key 和字符串(String)类型的 value:

HashMap<Integer, String> Sites = new HashMap<Integer, String>();

添加元素

HashMap 类提供类很多有用的方法,添加键值对(key-value)可以使用 put() 方法:

实例

// 引入 HashMap 类      
import java.util.HashMap;

public class RunoobTest {
    public static void main(String[] args) {
        // 创建 HashMap 对象 Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // 添加键值对
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        System.out.println(Sites);
    }
}

执行以上代码,输出结果如下:

{1=Google, 2=Runoob, 3=Taobao, 4=Zhihu}

以下实例创建一个整型(String)的 key 和 整型(String)的 value:

实例

// 引入 HashMap 类      
import java.util.HashMap;

public class RunoobTest {
    public static void main(String[] args) {
        // 创建 HashMap 对象 Sites
        HashMap<String, String> Sites = new HashMap<String, String>();
        // 添加键值对
        Sites.put("one", "Google");
        Sites.put("two", "Runoob");
        Sites.put("three", "Taobao");
        Sites.put("four", "Zhihu");
        System.out.println(Sites);
    }
}

执行以上代码,输出结果如下:

{four=Zhihu, one=Google, two=Runoob, three=Taobao}

访问元素

我们可以使用 get(key) 方法来获取 key 对应的 value:

实例

// 引入 HashMap 类      
import java.util.HashMap;

public class RunoobTest {
    public static void main(String[] args) {
        // 创建 HashMap 对象 Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // 添加键值对
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        System.out.println(Sites.get(3));
    }
}

执行以上代码,输出结果如下:

Taobao

删除元素

我们可以使用 remove(key) 方法来删除 key 对应的键值对(key-value):

实例

// 引入 HashMap 类      
import java.util.HashMap;

public class RunoobTest {
    public static void main(String[] args) {
        // 创建 HashMap 对象 Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // 添加键值对
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        Sites.remove(4);
        System.out.println(Sites);
    }
}

执行以上代码,输出结果如下:

{1=Google, 2=Runoob, 3=Taobao}

删除所有键值对(key-value)可以使用 clear 方法:

实例

// 引入 HashMap 类      
import java.util.HashMap;

public class RunoobTest {
    public static void main(String[] args) {
        // 创建 HashMap 对象 Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // 添加键值对
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        Sites.clear();
        System.out.println(Sites);
    }
}

执行以上代码,输出结果如下:

{}
posted @ 2020-10-21 14:16  While!true  阅读(46)  评论(0编辑  收藏  举报