美文网首页
HashMap(模拟底层数组+链表实现)

HashMap(模拟底层数组+链表实现)

作者: 寂静的春天1988 | 来源:发表于2019-01-13 20:30 被阅读0次
    package com.yidu.demo;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.Set;
    import java.util.TreeMap;
    import java.util.Vector;
    
    import org.omg.Messaging.SyncScopeHelper;
    /**
     * 模拟数组集合(底层数组实现)
     * @author Administrator
     */
    public class MyHashMap{
        private LinkedList[] arr;
        private int size;
        
        public void put(Object key,Object value){
            int hash=key.hashCode();
            hash=hash<0?-hash:hash;
            int a=hash%arr.length;
            Entry e=new Entry(key, value);
            if(arr[a]==null){
                LinkedList<Entry> l=new LinkedList<Entry>();
                l.add(e);
                arr[a]=l;
            }else{
                LinkedList<Entry> l=arr[a];
                for (int i = 0; i < l.size(); i++) {
                    if(l.get(i).key.equals(key)){
                        l.get(i).value=value;
                        return;
                    }
                }
                l.add(e);
            }
        }
        public Object get(Object key){
            int hash=key.hashCode();
            hash=hash<0?-hash:hash;
            int a=hash%arr.length;
            LinkedList<Entry> l=arr[a];
            for (int i = 0; i < l.size(); i++) {
                if(l.get(i).key.equals(key)){
                    return l.get(i).value;
                }
            }
            return null;
        }
        public void remove(Object key){
            int hash=key.hashCode();
            hash=hash<0?-hash:hash;
            int a=hash%arr.length;
            LinkedList<Entry> l=arr[a];
            for (int i = 0; i < l.size(); i++) {
                if(l.get(i).key.equals(key)){
                    l.get(i).value=null;
                }
            }
        }
        public MyHashMap(int initialCapacity){
            arr=new LinkedList[initialCapacity];
        }
        public MyHashMap(){
            this(10);
        }
        public static void main(String[] args) {
            
        }
    }
    class Entry{
        Object key;
        Object value;
        public Entry(Object key, Object value) {
            super();
            this.key = key;
            this.value = value;
        }
        public Entry() {
            super();
        }
    }
    ``

    相关文章

      网友评论

          本文标题:HashMap(模拟底层数组+链表实现)

          本文链接:https://www.haomeiwen.com/subject/ybildqtx.html