自制hashmap
package jjj;
public class MyHashMap<K, V> {
//initialization capacity
private int capacity = 10;
//total entities
private int size = 0;
private Entity<K, V>[] entities = null;
@SuppressWarnings("unchecked")
public MyHashMap() {
entities = new Entity[capacity];
}
public void put(K key, V value) {
if (key == null) {
throw new RuntimeException("The key is null");
}
reHash();
Entity<K, V> newEntity = new Entity<K, V>(key, value);
put(newEntity, this.entities, this.capacity);
}
private void put(Entity<K, V> newEntity, Entity<K, V>[] entities, int capacity) {
int index = newEntity.getKey().hashCode() % capacity;
Entity<K, V> entity = entities[index];
Entity<K, V> firstEntity = entities[index];
if (entity == null) {
entities[index] = newEntity;
size++;
} else {
if (newEntity.getKey().equals(entity.getKey())) {//Find the same key for the first entity, if find then replace the old value to new value
newEntity.setNext(entity.getNext());
newEntity.setPre(entity.getPre());
if (entity.getNext() != null) {
entity.getNext().setPre(newEntity);
}
entities[index] = newEntity;
} else if (entity.getNext() != null) {
while (entity.getNext() != null) {//Find the same key for all the next entity, if find then replace the old value to new value
entity = entity.getNext();
if (newEntity.getKey().equals(entity.getKey())) {
newEntity.setPre(entity.getPre());
newEntity.setNext(entity.getNext());
if (entity.getNext() != null) {
entity.getNext().setPre(newEntity);
}
entities[index] = newEntity;
return;
}
}
//Cannot find the same key, then insert the new entity at the header
newEntity.setNext(firstEntity);
newEntity.setPre(firstEntity.getPre());
firstEntity.setPre(newEntity);
entities[index] = newEntity;
size++;
} else {
//Cannot find the same key, then put the new entity in head
newEntity.setNext(firstEntity);
firstEntity.setPre(newEntity);
entities[index] = newEntity;
size++;
}
}
}
public V get(K key) {
if (key == null) {
throw new RuntimeException("The key is null");
}
int index = key.hashCode() % capacity;
Entity<K, V> entity = entities[index];
if (entity != null) {
if (entity.getKey().equals(key)) {
return entity.getValue();
} else {
entity = entity.getNext();
while (entity != null) {
if (entity.getKey().equals(key)) {
return entity.getValue();
}
entity = entity.getNext();
}
}
}
return null;
}
public void remove(K key) {
if (key == null) {
throw new RuntimeException("The key is null");
}
int index = key.hashCode() % capacity;
Entity<K, V> entity = entities[index];
if (entity != null) {
if (entity.getKey().equals(key)) {
if (entity.getNext() != null) {//remove the first entity
entity.getNext().setPre(entity.getPre());
entities[index] = entity.getNext();
entity = null;
} else {//empty this index
entities[index] = null;
}
size--;
} else {
entity = entity.getNext();
while (entity != null) {
if (entity.getKey().equals(key)) {
if (entity.getNext() != null) {
entity.getPre().setNext(entity.getNext());
entity.getNext().setPre(entity.getPre());
entity = null;
} else {
//release the found entity
entity.getPre().setNext(null);
entity = null;
}
size--;
return;
}
entity = entity.getNext();
}
}
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < capacity; i++) {
sb.append("index=").append(i).append("[");
boolean hasEntity = false;
Entity<K, V> entity = entities[i];
if (entity != null) {
hasEntity = true;
}
while (entity != null) {
sb.append("[").append(entity.getKey()).append("=").append(entity.getValue()).append("]").append(",");
entity = entity.getNext();
}
if (hasEntity) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append("]\n");
}
return sb.toString();
}
/**
* Simple re-hash strategy, if the size is bigger than capacity, then do re-hash action
*/
private void reHash() {
if (size >= capacity) {
int newCapacity = capacity * 2;
@SuppressWarnings("unchecked")
Entity<K, V>[] newEntities = new Entity[newCapacity];
for (int i = 0; i < capacity; i++) {
Entity<K, V> entity = entities[i];
while (entity != null) {
put(entity, newEntities, newCapacity);
entity = entity.getNext();
}
}
this.capacity = newCapacity;
this.entities = newEntities;
}
}
public static void main(String[] args) {
MyHashMap<String, String> map = new MyHashMap<String, String>();
map.put("one", "1");
map.put("two", "2");
map.put("three", "3");
map.put("four", "4");
map.put("five", "5");
map.put("six", "6");
map.put("seven", "7");
map.put("eight", "8");
map.put("nine", "9");
map.put("ten", "10");
System.out.println(map.get("one"));
System.out.println(map.get("two"));
System.out.println(map.get("three"));
System.out.println(map.get("four"));
System.out.println(map.get("five"));
System.out.println(map.get("six"));
System.out.println(map.get("seven"));
System.out.println(map.get("eight"));
System.out.println(map.get("nine"));
System.out.println(map.get("ten"));
System.out.println(map.toString());
map.remove("nine");
map.remove("three");
System.out.println(map.get("one"));
System.out.println(map.get("two"));
System.out.println(map.get("three"));
System.out.println(map.get("four"));
System.out.println(map.get("five"));
System.out.println(map.get("six"));
System.out.println(map.get("seven"));
System.out.println(map.get("eight"));
System.out.println(map.get("nine"));
System.out.println(map.get("ten"));
System.out.println(map.toString());
}
}
class Entity<K, V> {
private K key;
private V value;
private Entity<K, V> pre;
private Entity<K, V> next;
public Entity(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public Entity<K, V> getPre() {
return pre;
}
public void setPre(Entity<K, V> pre) {
this.pre = pre;
}
public Entity<K, V> getNext() {
return next;
}
public void setNext(Entity<K, V> next) {
this.next = next;
}
}
自制hashmap的更多相关文章
- 自制数据结构(容器)-java开发用的最多的ArrayList和HashMap
public class MyArrayList<E> { private int capacity = 10; private int size = 0; private E[] val ...
- Spring 依赖注入控制反转实现,及编码解析(自制容器)
定义: 在运行期,由外部容器动态的将依赖对象动态地注入到组件中. 两种方式: 手工装配 -set方式 -构造器 -注解方式 自动装配(不推荐) 1利用构造器 2set方法注入 dao: package ...
- OpenFaaS实战之八:自制模板(maven+jdk8)
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- HashMap与TreeMap源码分析
1. 引言 在红黑树--算法导论(15)中学习了红黑树的原理.本来打算自己来试着实现一下,然而在看了JDK(1.8.0)TreeMap的源码后恍然发现原来它就是利用红黑树实现的(很惭愧学了Ja ...
- HashMap的工作原理
HashMap的工作原理 HashMap的工作原理是近年来常见的Java面试题.几乎每个Java程序员都知道HashMap,都知道哪里要用HashMap,知道HashTable和HashMap之间 ...
- 计算机程序的思维逻辑 (40) - 剖析HashMap
前面两节介绍了ArrayList和LinkedList,它们的一个共同特点是,查找元素的效率都比较低,都需要逐个进行比较,本节介绍HashMap,它的查找效率则要高的多,HashMap是什么?怎么用? ...
- Java集合专题总结(1):HashMap 和 HashTable 源码学习和面试总结
2017年的秋招彻底结束了,感觉Java上面的最常见的集合相关的问题就是hash--系列和一些常用并发集合和队列,堆等结合算法一起考察,不完全统计,本人经历:先后百度.唯品会.58同城.新浪微博.趣分 ...
- 学习Redis你必须了解的数据结构——HashMap实现
本文版权归博客园和作者吴双本人共同所有,转载和爬虫请注明原文链接博客园蜗牛 cnblogs.com\tdws . 首先提供一种获取hashCode的方法,是一种比较受欢迎的方式,该方法参照了一位园友的 ...
- HashMap与HashTable的区别
HashMap和HashSet的区别是Java面试中最常被问到的问题.如果没有涉及到Collection框架以及多线程的面试,可以说是不完整.而Collection框架的问题不涉及到HashSet和H ...
随机推荐
- C# 中的集合(Array/ArrayList/List<T>/HashTable/Dictionary)
int [] numbers = new int[5]; // 长度为5,元素类型为 int. string[,] names = new string[5,4]; // 5*4 的二维数组 byte ...
- Android Studio 常用快捷键和使用技巧
Android Studio 1.Ctrl+E,可以显示最近编辑的文件列表 2.Shift+Click可以关闭文件 3.Ctrl+[或]可以跳到大括号的开头结尾 4.Ctrl+Shift+Backsp ...
- 『cs231n』作业3问题2选讲_通过代码理解LSTM网络
LSTM神经元行为分析 LSTM 公式可以描述如下: itftotgtctht=sigmoid(Wixxt+Wihht−1+bi)=sigmoid(Wfxxt+Wfhht−1+bf)=sigmoid( ...
- TCP/IP四层与OSI七层模型
OSI七层和TCP/IP四层的关系 1.1 OSI引入了服务.接口.协议.分层的概念,TCP/IP借鉴了OSI的这些概念建立TCP/IP模型. 1.2 OSI先有模型,后有协议,先有标准,后进行实 ...
- Leetcode 90
// 重复元素在去重的时候会出现顺序不同去不了重,这时候需要对add进行排序class Solution { public: vector<vector<int>> subse ...
- 24.2 网络编程基础——System.Net 命名空间
使用C#进行网络编程时,通常要用到: System. Net 命名空间. System. Net. Sockets 命名空间. System. Net. Mail 命名空间. 24.2.1 Sy ...
- consumer的DubboResponseTimeoutScanTimer线程
考虑这样一种情况,由于网络延时,consumer先抛出超时异常,一段时间后又收到了已经超时的响应,dubbo是怎么处理的? 拆分为3步看: 1. consumer的DubboResponseTimeo ...
- 自定义Spark Partitioner提升es-hadoop Bulk效率
http://www.jianshu.com/p/cccc56e39429/comments/2022782 和 https://github.com/elastic/elasticsearch-ha ...
- win7 安装express
1.以管理员身份打开cmd(避免出错) npm install -g express-generator@4 Start the server: npm start 链接,github官网说明 htt ...
- java并发编程:线程安全管理类--原子操作类--AtomicReferenceFieldUpdater<T,V>
1.类 AtomicReferenceFieldUpdater<T,V> public abstract class AtomicReferenceFieldUpdater<T,V& ...