自定义map(map实现原理)

时间:2022-03-12 16:05:14
package com.bean;

public class MyMap {
	 
    private Entry[] data = new Entry[100];
    private int size;

    public Object put(Object key, Object value) {
           // 检查key是否存在,存在则覆盖
           for (int i = 0; i < size; i++) {
                  if (key.equals(data [i].key)) {
                       Object oldValue = data[i].value ;
                        data[i].value = value;
                        return oldValue;
                 }
          }
           
          Entry e = new Entry(key, value);
           data[size ] = e;
           size++;
           
           return null;
   }

    public Object get(Object key) {
           for (int i = 0; i < size; i++) {
                  if (key.equals(data [i].key)) {
                        return data [i].value;
                 }
          }

           return null;
   }
    
    public int size() {
           return size ;
   }
    
    private class Entry {
          Object key;
          Object value;

           public Entry(Object key, Object value) {
                  this.key = key;
                  this.value = value;
          }

   }
}