概述
HashMap 是基于数组 + 链表/红黑树实现的,支持自动扩容。
优点:高效的查找/插入(平均O(1),最差O(n))、动态扩容、支持null键和null值
缺点:哈希冲突可能影响性能、线程不安全、内存占用较高
适合的场景:适合单线程高频查询场景
是否线程安全:HashMap是线程不安全的,如果需要线程安全,推荐使用 ConcurrentHashMap。用 Collections synchronizedMap() 也可以实现线程安全。
千里之行,始于足下
HashMap 是基于数组 + 链表/红黑树实现的,支持自动扩容。
优点:高效的查找/插入(平均O(1),最差O(n))、动态扩容、支持null键和null值
缺点:哈希冲突可能影响性能、线程不安全、内存占用较高
适合的场景:适合单线程高频查询场景
是否线程安全:HashMap是线程不安全的,如果需要线程安全,推荐使用 ConcurrentHashMap。用 Collections synchronizedMap() 也可以实现线程安全。
本人从事 Java 开发工作,至今有将近7年的时间。
常用的技术栈有 Spring、MyBatis、HSF、MetaQ、SchedulerX、Switch、Diamond、TDDL、ODPS 等。
前端方面,熟悉 React、Vue 的开发,目前常用的是 React。
服务器方面,熟悉主流 Linux 系统、树莓派等。
测试机:Mac Pro 16GB; 2.6GHz 六核 Intel Core i7
public class MatchTest {
/*
* 判读一个字符串是否是纯数字,试了如下两种方式,以为会快点
* 还有一种方式更快,那就是 Character.isDigit 那种
*/
private static final Integer TEST_COUNT = 100000000;
private static final String TEST_STR = String.valueOf(Long.MAX_VALUE);
/**
* 测试结果: true, 耗时: 13345ms
*/
@Test
public void stringMatches() {
long startTime = System.currentTimeMillis();
for (int i = 0; i < TEST_COUNT; i++) {
TEST_STR.matches("[+0-9]");
}
System.out.printf("测试结果: %s, 耗时: %sms\n",
TEST_STR.matches("[0-9]+"),
(System.currentTimeMillis() - startTime));
}
/**
* 测试结果: true, 耗时: 8828ms
*/
@Test
public void patternMatches() {
long startTime = System.currentTimeMillis();
Pattern number = Pattern.compile("[0-9]+");
for (int i = 0; i < TEST_COUNT; i++) {
number.matcher(TEST_STR).matches();
}
System.out.printf("测试结果: %s, 耗时: %sms\n",
number.matcher(TEST_STR).matches(),
(System.currentTimeMillis() - startTime));
}
/**
* 测试结果: true, 耗时: 11ms
*/
@Test
public void isDigitMatches() {
long startTime = System.currentTimeMillis();
for (int i = 0; i < TEST_COUNT; i++) {
isNumber(TEST_STR);
}
System.out.printf("测试结果: %s, 耗时: %sms\n",
isNumber(TEST_STR),
(System.currentTimeMillis() - startTime));
}
private static boolean isNumber(String str) {
if (str == null || str.isEmpty()) {
return false;
}
for (int i = 0, len = str.length(); i < len; i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
}
ArrayList 是基于数组实现的动态列表,支持自动扩容。
优点:高效的随机访问O(1)、动态扩容、内存连续
缺点:插入/删除性能较差O(n)、扩容开销较大、内存浪费(预留空间)
适合的场景:随机访问多、数据量变化小的场景。如果频繁插入/删除,推荐使用 LinkedList。
是否线程安全:ArrayList是线程不安全的,如果需要线程安全,可使用 CopyOnWriteArrayList 或 Collections.synchronizedList。
本文结合 JDK 17 的源码展开,与其他版本相比变化不大。
本文着重讲 GitHub 自动化部署,创建 VuePress 官方文档比较详细,就不说啦。
https://v2.vuepress.vuejs.org/zh/
当然呢,可以参考我的项目