自己实现一个Map

 1 public class MyMap<K, V> {
 2     private Node<K, V>[] nodes;//定义一个Node数组保存键值对
 3     private  int size;//逻辑长度
 4     //内部静态类,用于保存key,value值
 5     private static class Node<K, V>{
 6         K key;
 7         V value;
 8         Node(K key, V value){
 9             this.key = key;
10             this.value = value;
11         }
12     }
13     //存储元素
14     public void put(K key , V value){
15         if(nodes == null) {
16             nodes = new Node[10];
17         }
18         int index = indexOfKey(key);
19         if(index != -1){
20             nodes[index].value = value;
21         }else {
22             nodes[size] = new Node<>(key, value);
23             size++;
24         }
25     }
26     
27     public V get(K key){
28         int index = indexOfKey(key);
29         if(index != -1){
30             return nodes[index].value;
31         }
32         return null;
33     }
34     
35     public int size(){
36         return size;
37     }
38     
39     //查找key是否存在已经存在数组nodes中,如果找不到返回-1,找到则返回数组下标
40     private int indexOfKey(K key){
41         for(int i = 0; i < nodes.length; i++){
42             if(key.equals(this.nodes[i].key)){
43                 return i;
44             }
45         }
46         return -1;
47     }
48 }

猜你喜欢

转载自www.cnblogs.com/qmillet/p/12501133.html