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

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 l=new LinkedList();
            l.add(e);
            arr[a]=l;
        }else{
            LinkedList 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 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 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(模拟底层数组+链表实现))