File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .HashMap ;
2
+
3
+ public class HashMapDemo {
4
+ /**
5
+ * HashMap 由数组和链表实现,键值对加入时根据键计算数组下标,然后插入链表头部,O(1) 复杂度。查询时同样根据键找到数组下标,然后遍历链表进行查找。
6
+ * JDK 1.8 后,当链表长度大于 8 时,将链表改为红黑树实现,将查询链表的 O(n) 降为 O(logN) 复杂度。
7
+ * HashMap 并不是线程安全的,可使用 ConcurrentHashMap。
8
+ * @param args
9
+ */
10
+ public static void main (String [] args ) {
11
+ // 创建一个 HashMap
12
+ HashMap <String , Double > map = new HashMap <>();
13
+
14
+ // 插入键值对
15
+ map .put ("语文" , 130.0 );
16
+ map .put ("数学" , 100.0 );
17
+ map .put ("物理" , 138.0 );
18
+
19
+ // 获取键值对数量
20
+ System .out .println (map .size ());
21
+
22
+ // 根据键获取值
23
+ System .out .println (map .get ("物理" ));
24
+
25
+ // 更新某个键的值
26
+ map .put ("物理" , 90.0 );
27
+
28
+ // 删除键值对
29
+ map .remove ("物理" );
30
+
31
+ // 遍历一个 HashMap
32
+ map .forEach ((key , val ) -> System .out .println (key + "成绩: " + val ));
33
+ }
34
+ }
You can’t perform that action at this time.
0 commit comments