一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專(zhuān)注于服務(wù)器技術(shù)及軟件下載分享
分類(lèi)導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語(yǔ)言|JavaScript|易語(yǔ)言|vb.net|

服務(wù)器之家 - 編程語(yǔ)言 - Java教程 - ArrayList和HashMap如何自己實(shí)現(xiàn)實(shí)例詳解

ArrayList和HashMap如何自己實(shí)現(xiàn)實(shí)例詳解

2020-07-19 12:3551CTO Java教程

這篇文章主要介紹了 ArrayList和HashMap如何自己實(shí)現(xiàn)的相關(guān)資料,需要的朋友可以參考下

 ArrayListHashMap

ArrayList的存儲(chǔ)就是一個(gè)數(shù)組,

HashMap的存儲(chǔ)是一個(gè)數(shù)組加一個(gè)鏈表,

ArrayList和HashMap如何自己實(shí)現(xiàn)實(shí)例詳解

以下實(shí)現(xiàn)的MyArrayList及MyHashMap,在實(shí)際的工作中都是用不上的,最有可能用得到的地方就是面試找工作以及忽悠別人了。工作中雖然用不上,但是并不代表沒(méi)有用,它可以幫助我們?nèi)ダ斫馑麄兊膶?shí)現(xiàn)原理,等實(shí)現(xiàn)完后再去仔細(xì)查看JDK中的源碼,就會(huì)發(fā)現(xiàn)別人實(shí)現(xiàn)當(dāng)中那些可供學(xué)習(xí)的地方。

MyArrayList

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
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;
  }
 
}

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 精品久久久久久无码人妻国产馆 | 亚洲成人99 | www.午夜剧场 | 免费午夜影院 | 精品一卡2卡3卡4卡5卡亚洲 | 美人老师沦为 | 国产精品不卡高清在线观看 | 国产精品久久久久久爽爽爽 | 日韩视频在线观看中字 | 韩国一级淫片特黄特刺激 | 猫扑俩性 | 性吟网| 99re8在线精品视频免费播放 | 免费一级日本c片完整版 | a级特黄毛片免费观看 | 色婷婷综合缴情综六月 | 非洲黑人又大粗gay 非洲黑人bbwbbwbbw | 男人和女人日 | 女人被男人躁得好爽免费视频 | 日本一区二区在线不卡 | 好紧好爽再叫浪一点点潘金莲 | 四虎影视免费观看 | 欧美人禽杂交狂配无删完整 | 成人女人天堂午夜视频 | 高清一区 | 日韩在线免费播放 | www.四色 | 无码骚夜夜精品 | 日韩欧美国产免费看清风阁 | 色多多视频网站 | 亚洲国产成人久久77 | 草久社区| 亚洲香蕉综合在人在线视看 | 精品亚洲欧美中文字幕在线看 | 91精品久久一区二区三区 | 精品国产一区二区三区久久影院 | 日韩香蕉网 | 日本乱人伦中文在线播放 | 国产区最新 | 精品精品国产yyy5857香蕉 | 色播艾小青国产专区在线播放 |