当前位置: 移动技术网 > IT编程>开发语言>Java > HashMap概述及其三种遍历方式

HashMap概述及其三种遍历方式

2019年02月26日  | 移动技术网IT编程  | 我要评论

一、hashmap概述;

1.hashmap是一个散列表,它存储的是键值对(key-value)映射;

2.hashmap继承abstractmap,实现了map,cloneable,serializable接口;

3.hashmap的实现不是同步的,线程不安全,但是效率高;

4.hashmap允许null键和null值,是基于哈希表的map接口实现;

5.哈希表的作用是用来保证键的唯一性;

6.hashmap的实例有两个参数影响其性能:初试容量和加载因子,当哈希表中的条目数超出加载因子与当前容量的乘积时,要对哈希表进行rehash操作(即重建内部数据结构),容量扩大约为之前的两倍,加载因子默认值为0.75;

二、hashmap的三种遍历方式;

第一种:遍历hashmap的entryset键值对集合

1.通过hashmap.entryset()得到键值对集合;

2.通过迭代器iterator遍历键值对集合得到key值和value值;

package com.xyfer;

import java.util.hashmap;
import java.util.iterator;
import java.util.map;

public class hashmaptest {

    public static void main(string[] args) {
        // 创建一个key和value均为string的map集合
        map<string, string> map = new hashmap<string, string>();
        map.put("1", "11");
        map.put("2", "22");
        map.put("3", "33");
        // 键和值
        string key = null;
        string value = null;
        // 获取键值对的迭代器
        iterator it = map.entryset().iterator();
        while (it.hasnext()) {
            map.entry entry = (map.entry) it.next();
            key = (string) entry.getkey();
            value = (string) entry.getvalue();
            system.out.println("key:" + key + "---" + "value:" + value);
        }

    }

}

控制台打印结果:

第二种:遍历hashmap键的set集合获取值;

1.通过hashmap.keyset()获得键的set集合;

2.遍历键的set集合获取值;

package com.xyfer;

import java.util.hashmap;
import java.util.iterator;
import java.util.map;

public class hashmaptest {

    public static void main(string[] args) {
        // 创建一个key和value均为string的map集合
        map<string, string> map = new hashmap<string, string>();
        map.put("1", "11");
        map.put("2", "22");
        map.put("3", "33");
        // 键和值
        string key = null;
        string value = null;
        // 获取键集合的迭代器
        iterator it = map.keyset().iterator();
        while (it.hasnext()) {
            key = (string) it.next();
            value = (string) map.get(key);
            system.out.println("key:" + key + "---" + "value:" + value);
        }

    }

}

控制台打印结果:

第三种:遍历hashmap“值”的集合;

1.通过hashmap.values()得到“值”的集合

2.遍历“值”的集合;

package com.xyfer;

import java.util.hashmap;
import java.util.iterator;
import java.util.map;

public class hashmaptest {

    public static void main(string[] args) {
        // 创建一个key和value均为string的map集合
        map<string, string> map = new hashmap<string, string>();
        map.put("1", "11");
        map.put("2", "22");
        map.put("3", "33");
        // 值
        string value = null;
        // 获取值集合的迭代器
        iterator it = map.values().iterator();
        while (it.hasnext()) {
            value = (string) it.next();
            system.out.println("value:" + value);
        }
    }
}

控制台打印结果:

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网