ArrayList和HashMap如何自己实现实例详解
发布时间 - 2026-01-10 22:09:50 点击率:次ArrayList和HashMap

ArrayList的存储就是一个数组,
HashMap的存储是一个数组加一个链表,
以下实现的MyArrayList及MyHashMap,在实际的工作中都是用不上的,最有可能用得到的地方就是面试找工作以及忽悠别人了。工作中虽然用不上,但是并不代表没有用,它可以帮助我们去理解他们的实现原理,等实现完后再去仔细查看JDK中的源码,就会发现别人实现当中那些可供学习的地方。
MyArrayList
public class MyArrayList<E> {
private int capacity = 10;
private int size = 0;
private E[] values = null;
@SuppressWarnings("unchecked")
public MyArrayList() {
values = (E[]) new Object[capacity];
}
@SuppressWarnings("unchecked")
public MyArrayList(int capacity) {
this.capacity = capacity;
values = (E[]) new Object[this.capacity];
}
public void put(E e) {
if (e == null) {
throw new RuntimeException("The value should not be null.");
}
if (size >= capacity) {
enlargeCapacity();
}
values[size] = e;
size++;
}
public E get(int index) {
if (index >= size) {
throw new RuntimeException("The index:" + index + " is out of band.");
}
return values[index];
}
public void remove(int index) {
if (index >= size) {
throw new RuntimeException("The index:" + index + " is out of band.");
}
for (int i = index; i < size - 1; i++) {
values[i] = values[i + 1];
}
values[size - 1] = null;
size--;
}
@SuppressWarnings("unchecked")
private void enlargeCapacity() {
capacity = capacity * 2;
E[] tmpValues = (E[]) new Object[capacity];
System.arraycopy(values, 0, tmpValues, 0, size);
values = tmpValues;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < size; i++) {
sb.append(values[i]).append(",");
}
if (size > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append("]");
return sb.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
MyArrayList<String> myList = new MyArrayList<String>();
myList.put("1");
myList.put("2");
myList.put("3");
myList.put("4");
myList.put("5");
myList.put("6");
myList.put("7");
myList.put("8");
myList.put("9");
myList.remove(7);
System.out.println(myList.toString());
}
}
MyHashMap
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;
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
# ArrayList和HashMap
# 如何自己实现
# ArrayList
# HashMap
# 浅析java中ArrayList与Vector的区别以及HashMap与Hashtable的区别
# 深入探讨JavaScript的最基本部分之执行上下文
# 谈谈JavaScript中super(props)的重要性
# JavaScript常用工具方法封装
# Java多线程实战之交叉打印的两种方法
# Java多线程实战之单例模式与多线程的实例详解
# JavaTCP上传文本文件代码
# Java五子棋AI实现代码
# Javascript迭代、递推、穷举、递归常用算法实例讲解
# ArrayList及HashMap的扩容规则讲解
# 不上
# 都是
# 是一个
# 他们的
# 就会
# 希望能
# 人了
# 它可以
# 可供
# 再去
# 并不代表
# 谢谢大家
# 完后
# 链表
# 在实际
# 有可能用
# Object
# void
# throw
# put
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
如何登录建站主机?访问步骤全解析
Laravel如何使用Passport实现OAuth2?(完整配置步骤)
JavaScript如何实现音频处理_Web Audio API如何工作?
Laravel如何使用集合(Collections)进行数据处理_Laravel Collection常用方法与技巧
高端建站如何打造兼具美学与转化的品牌官网?
Laravel如何处理和验证JSON类型的数据库字段
JavaScript如何实现倒计时_时间函数如何精确控制
黑客如何通过漏洞一步步攻陷网站服务器?
香港服务器选型指南:免备案配置与高效建站方案解析
Laravel Vite是做什么的_Laravel前端资源打包工具Vite配置与使用
教你用AI将一段旋律扩展成一首完整的曲子
如何在阿里云完成域名注册与建站?
如何用PHP工具快速搭建高效网站?
Laravel Artisan命令怎么自定义_创建自己的Laravel命令行工具完全指南
Laravel Sail是什么_基于Docker的Laravel本地开发环境Sail入门
Laravel如何实现图片防盗链功能_Laravel中间件验证Referer来源请求【方案】
VIVO手机上del键无效OnKeyListener不响应的原因及解决方法
软银砸40亿美元收购DigitalBridge 强化AI资料中心布局
微博html5版本怎么弄发语音微博_语音录制入口及时长限制操作【教程】
Laravel Debugbar怎么安装_Laravel调试工具栏配置指南
微博html5版本怎么弄发超话_超话进入入口及发帖格式要求【教程】
电商网站制作多少钱一个,电子商务公司的网站制作费用计入什么科目?
jquery插件bootstrapValidator表单验证详解
小视频制作网站有哪些,有什么看国内小视频的网站,求推荐?
东莞市网站制作公司有哪些,东莞找工作用什么网站好?
悟空识字怎么关闭自动续费_悟空识字取消会员自动扣费步骤
如何快速搭建高效WAP手机网站吸引移动用户?
laravel怎么使用数据库工厂(Factory)生成带有关联模型的数据_laravel Factory生成关联数据方法
如何快速生成高效建站系统源代码?
php json中文编码为null的解决办法
智能起名网站制作软件有哪些,制作logo的软件?
Android自定义控件实现温度旋转按钮效果
Android okhttputils现在进度显示实例代码
详解Nginx + Tomcat 反向代理 如何在高效的在一台服务器部署多个站点
如何在阿里云香港服务器快速搭建网站?
如何在IIS中配置站点IP、端口及主机头?
Laravel Blade组件怎么用_Laravel可复用视图组件的创建与使用
如何为不同团队 ID 动态生成多个非值班状态按钮
如何在香港服务器上快速搭建免备案网站?
宙斯浏览器文件分类查看教程 快速筛选视频文档与图片方法
JS实现鼠标移上去显示图片或微信二维码
Laravel怎么多语言本地化设置_Laravel语言包翻译与Locale动态切换【手册】
laravel怎么为应用开启和关闭维护模式_laravel应用维护模式开启与关闭方法
详解CentOS6.5 安装 MySQL5.1.71的方法
如何用y主机助手快速搭建网站?
PHP 实现电台节目表的智能时间匹配与今日/明日轮播逻辑
如何用搬瓦工VPS快速搭建个人网站?
Edge浏览器怎么启用睡眠标签页_节省电脑内存占用优化技巧
公司网站制作需要多少钱,找人做公司网站需要多少钱?
百度浏览器ai对话怎么关 百度浏览器ai聊天窗口隐藏

