HashMap介绍

HashMap是一个基于Map的集合类,用于存储Key和Value的键值对。

通常用HashMap<Key, Value> or HashMap<K, V>标识。

这个类不保证元素的顺序。

HashMap和HashTable很类似,除了它是非线程安全和允许null值(null值和null Key)这2个特点。

不保证元素顺序意思是它不会按照你插入的顺序返回。它不会对key和value进行排序。

类定义

public class HashMap<K,V>

extends AbstractMap<K,V>

implements Map<K,V>, Cloneable, Serializable

例子介绍

package com.dylan.collection;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set; /**
* @author xusucheng
* @create 2018-01-31
**/
public class HashMapExample {
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());
} }
}

常用方法

增:put, putAll

删:clear, remove

改:put

查:isEmpty, get, keySet, size, containsKey

如何给HashMap的键值对排序

1.按key排序

package com.dylan.collection;

import java.util.*;

/**
* @author xusucheng
* @create 2018-01-31
**/
public class HashMapSortByKey {
public static void main(String[] args) { HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(5, "A");
hmap.put(11, "C");
hmap.put(4, "Z");
hmap.put(77, "Y");
hmap.put(9, "P");
hmap.put(66, "Q");
hmap.put(0, "R"); System.out.println("Before Sorting:");
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Map<Integer, String> map = new TreeMap<Integer, String>(hmap);
System.out.println("After Sorting:");
Set set2 = map.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator2.next();
System.out.print(me2.getKey() + ": ");
System.out.println(me2.getValue());
}
}
}

2.按value排序

package com.dylan.collection;

import java.util.*;

/**
* @author xusucheng
* @create 2018-01-31
**/
public class HashMapSortByValue {
public static void main(String[] args) {
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(5, "A");
hmap.put(11, "C");
hmap.put(4, "Z");
hmap.put(77, "Y");
hmap.put(9, "P");
hmap.put(66, "Q");
hmap.put(0, "R");
System.out.println("Before Sorting:");
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry me = (Map.Entry) iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Map<Integer, String> map = sortByValues(hmap);
System.out.println("After Sorting:");
Set set2 = map.entrySet();
Iterator iterator2 = set2.iterator();
while (iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry) iterator2.next();
System.out.print(me2.getKey() + ": ");
System.out.println(me2.getValue());
} } private static HashMap sortByValues(HashMap map) {
List list = new LinkedList(map.entrySet());
// Defined Custom Comparator here
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
}); // Here I am copying the sorted list in HashMap
// using LinkedHashMap to preserve the insertion order
HashMap sortedHashMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedHashMap.put(entry.getKey(), entry.getValue());
}
return sortedHashMap;
}
}

序列化/反序列化HashMap

import java.io.*;
import java.util.HashMap;
public class Details
{
public static void main(String [] args)
{
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
//Adding elements to HashMap
hmap.put(11, "AB");
hmap.put(2, "CD");
hmap.put(33, "EF");
hmap.put(9, "GH");
hmap.put(3, "IJ");
try
{
FileOutputStream fos =
new FileOutputStream("hashmap.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(hmap);
oos.close();
fos.close();
System.out.printf("Serialized HashMap data is saved in hashmap.ser");
}catch(IOException ioe)
{
ioe.printStackTrace();
}
}
} import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Student
{
public static void main(String [] args)
{
HashMap<Integer, String> map = null;
try
{
FileInputStream fis = new FileInputStream("hashmap.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
map = (HashMap) ois.readObject();
ois.close();
fis.close();
}catch(IOException ioe)
{
ioe.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized HashMap..");
// Display content using Iterator
Set set = map.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("key: "+ mentry.getKey() + " & Value: ");
System.out.println(mentry.getValue());
}
}
}

HashMap和HashTable区别

HashMap和Hashtable都实现了Map接口,但决定用哪一个之前先要弄清楚它们之间的分别。

主要的区别有:线程安全性,同步(synchronization),以及速度。

1. HashMap几乎可以等价于Hashtable,除了HashMap是非synchronized的,并可以接受null(HashMap可以接受为null的键

值(key)和值(value),而Hashtable则不行)。

2. HashMap是非synchronized,而Hashtable是synchronized,这意味着Hashtable是线程安全的,多个线程可以共享一个

Hashtable;

而如果没有正确的同步的话,多个线程是不能共享HashMap的。Java 5提供了ConcurrentHashMap,它是HashTable的替代,

比HashTable的扩展性更好。

3. 另一个区别是HashMap的迭代器(Iterator)是fail-fast迭代器,而Hashtable的enumerator迭代器不是fail-fast的。

所以当有其它线程改变了HashMap的结构(增加或者移除元素),将会抛出ConcurrentModificationException,

但迭代器本身的remove()方法移除元素则不会抛出ConcurrentModificationException异常。但这并不是一个一定发生的行为,

要看JVM。

这条同样也是Enumeration和Iterator的区别。

4. 由于Hashtable是线程安全的也是synchronized,所以在单线程环境下它比HashMap要慢。如果你不需要同步,只需要单一

线程,那么使用HashMap性能要好过Hashtable。

HashMap不能保证随着时间的推移Map中的元素次序是不变的。

Java集合框架学习(八) HashMap详解的更多相关文章

  1. Java集合框架学习(一)List

    先附一张Java集合框架图. 从上面的集合框架图可以看到,Java集合框架主要包括两种类型的容器,一种是集合(Collection),存储一个元素集合,另一种是图(Map),存储键/值对映射.Coll ...

  2. Java集合框架学习

    集合框架 集合框架的目标 该框架必须是高性能的.基本集合(动态数组,链表,树,哈希表)的实现必须是高效的. 该框架允许 不同类型的集合,以类似的方式工作,具有高度的互操作性. 对一个集合的扩展和适应必 ...

  3. Java 集合Collection与List的详解

    1.什么是集合 存储对象的容器,面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,存储对象,集合是存储对象最常用的一种方式. 集合的出现就是为了持有对象.集合中可以存储任意类型的 ...

  4. java集合的方法及使用详解

    一.java集合的分类及相互之间的关系 Collection接口:向下提供了List和Set两个子接口 |------List接口:存储有序的,存储元素可以重复 |------ArrayList(主要 ...

  5. Java集合框架之三:HashMap源码解析

    版权声明:本文为博主原创文章,转载请注明出处,欢迎交流学习! HashMap在我们的工作中应用的非常广泛,在工作面试中也经常会被问到,对于这样一个重要的集合模型我们有必要弄清楚它的使用方法和它底层的实 ...

  6. 【java基础 11】java集合框架学习

    导读:本篇博客主要是从整体上了解java的集合框架,然后主要介绍几个自己在项目中用到的结构,比如说:hashtable.hashmap.hashset.arraylist等! 一.宏观预览 从宏观上看 ...

  7. Java容器解析系列(11) HashMap 详解

    本篇我们来介绍一个最常用的Map结构--HashMap 关于HashMap,关于其基本原理,网上对其进行讲解的博客非常多,且很多都写的比较好,所以.... 这里直接贴上地址: 关于hash算法: Ha ...

  8. Java集合框架学习笔记

    集合类的由来:对象用于封装特有数据,对象多了需要存储,如果对象的长度不确定,就使用集合存储. 集合特点1.用于存储对象的容器.2.集合的长度可变.3.集合中不可以存储基本类型 集合容器因为内部的数据结 ...

  9. Java后端框架之Spring Boot详解,文末有Java分布式实战项目视频可取

    在 Java 后端框架繁荣的今天,Spring 框架无疑是最最火热,也是必不可少的开源框架,更是稳坐 Java 后端框架的龙头老大. 用过 Spring 框架的都知道 Spring 能流行是因为它的两 ...

  10. Java集合框架学习总结

    转自:http://www.cnblogs.com/oubo/archive/2012/01/07/2394639.html Oubo的博客 以下介绍经常使用的集合类,这里不介绍集合类的使用方法,只介 ...

随机推荐

  1. [转帖]JVM系列之:再谈java中的safepoint

    https://zhuanlan.zhihu.com/p/171625395 safepoint是什么 java程序里面有很多很多的java线程,每个java线程又有自己的stack,并且共享了hea ...

  2. oceanbase部署维护命令学习

    oceanbase部署维护命令学习 背景 之前学习过TIDB数据库, 最近又准备学习一下Oceanbase数据库 发现其实两者还是比较相似的. 比较大的区别在于. TiDB是完全开源的, 并且比较明确 ...

  3. [转帖]一文说清 Linux System Load

    https://zhuanlan.zhihu.com/p/447661302 双十一压测过程中,常见的问题之一就是load 飙高,通常这个时候业务上都有受影响,比如服务rt飙高,比如机器无法登录,比如 ...

  4. [转帖]zookeeper三节点集群搭建

    https://www.jianshu.com/p/1dcfbf45383b 下载zookeeper Apache源 http://archive.apache.org/dist/zookeeper/ ...

  5. [转帖]Redis 核心篇:唯快不破的秘密

    文章系转载,方便整理和归纳,源文地址:https://z.itpub.net/article/detail/4B5A03BDDBE9A2BC3E080E278FE4D21E 以下文章来源于码哥字节 , ...

  6. [转帖]讨论在 Linux Control Groups 中运行 Java 应用程序的暂停问题原创

    https://heapdump.cn/article/1930426 说明 本篇原文来自 LinkedIn 的 Zhenyun Zhuang,原文:Application Pauses When R ...

  7. MYSQL 日志参数与性能的关系

    1. 先看一下mysql技术内幕 innodb存储引擎的一个结果 以及各个参数的含义

  8. OpenPower服务使用node-exporter prometheus以及grafana进行性能监控的流程

    OpenPower服务器性能监控操作流程 1. 前言 最近看了很多prometheus以及influxdb进行性能监控的帖子,简单学习了下influxdb是一个单纯的时序数据库,prometheus是 ...

  9. 提升vscode的搜索速度

    在全局搜索速度上vscode比pycharm要慢不少,尤其是对于我们这种近二十年历史的项目代码来说特别明显,所以这里记录一下我是如何加快vscode的搜索速度的. 官方的搜索建议 https://co ...

  10. 英伟达系列显卡大解析B100、H200、L40S、A100、A800、H100、H800、V100如何选择,含架构技术和性能对比带你解决疑惑

    英伟达系列显卡大解析B100.H200.L40S.A100.A800.H100.H800.V100如何选择,含架构技术和性能对比带你解决疑惑 近期,AIGC领域呈现出一片繁荣景象,其背后离不开强大算力 ...