手写基本容器——HashMap和TreeMap(四)


一、HashMap

底层实现

结构:数组+链表的结构
数组:默认为16个大小
链表:存在每个数组里,如果数组里面有元素的话,就存在上一个的next的位置,再有继续存在上一个的next的位置,这样就会构成一个单项的链子;
转换:当链表变的很长的时候,链表的结构就会转换为红黑二叉树;

Hash码:生产数据的时候生成的一个码,用来生成hash值
hash值:用来确定存储在数组的哪个位置的数(也就是index)

流程:HashMap生成的时候,就会产生HashCode码,然后将哈希码进行散列的算法,可以的得到一个Hash值,这样之后,就会确定这个put的存储位置,如果有相同的Hash值得话,就会,将他们放在了对应的存在值得next的后面,这样就形成了一个小型的链表,但是如果当他们超过一定数量的时候就会产生边的很慢,所以JDK8以后将他们超过一定个数后的链表转化为红黑二叉树,进行存储,大大的加快了存储的效率

HashMap在和HashTable在建立的时候,都是通过“位桶数组”来进行建立的,大约建立了2的倍数,一般为16个数组,所以当我们去获取这个hashcode的key的时候,实现获取他的hashcode来进行计算,然后找到他们并且equal的方法找到那个元素,返回true,

我们先观察一下JDK11的源码

我们可以看出来,他们的值是不能进行改变的或者只能改变一次,我们可不一定要按照他们的写法来进行编写,可以按照自己的方式

/***
 * 核心的代码就如下面的Node一样
 */
static class Node<K,V> implements Map.Entry<K,V> {
  final int hash;
  final K key;
  V value;
  Node<K,V> next;

  Node(int hash, K key, V value, Node<K,V> next) {
      this.hash = hash;
      this.key = key;
      this.value = value;
      this.next = next;
  }

  public final K getKey()        { return key; }
  public final V getValue()      { return value; }
  public final String toString() { return key + "=" + value; }

  public final int hashCode() {
      return Objects.hashCode(key) ^ Objects.hashCode(value);
  }

  public final V setValue(V newValue) {
      V oldValue = value;
      value = newValue;
      return oldValue;
  }

1、建立Node

node 为数据的存储结构类似于链表,但是没有前一个的跳转,只能往后进行寻找,我们这里让他可以进行修改

/***
 * 自定义一个HashMap的实现方式
 * @author starwang
 *
 */
public class Node2 {
	private int hash;
	private Object key;
	private Object Value;
	private Node2 next;
	public int getHash() {
		return hash;
	}
	public void setHash(int hash) {
		this.hash = hash;
	}
	public Object getKey() {
		return key;
	}
	public void setKey(Object key) {
		this.key = key;
	}
	public Object getValue() {
		return Value;
	}
	public void setValue(Object value) {
		Value = value;
	}
	public Node2 getNext() {
		return next;
	}
	public void setNext(Node2 next) {
		this.next = next;
	}
	
	
}


2、写出基本的put和toString的方法

Node2[] table;//位桶数组
	int size;
	Boolean replaceKey = false;
	
	public myHashMap3(int a){
		table = new Node2[a];
	}
	public myHashMap3() {
		table = new Node2[16];
	}
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append('[');
		for(int i=0;i<table.length;i++) {
			Node2 temp= table[i];
			sb.append('{');
			while(temp!=null) {
				sb.append(temp.getKey()+":"+temp.getValue()+",");
				temp = temp.getNext();
			}
			sb.setCharAt(sb.length()-1, '}');
			sb.append(",");
		}
		sb.setCharAt(sb.length()-1, ']');
		
		
		return  sb.toString();
	}
	public Object get(Object key) {
		int hash = myHash(key, table.length);
		Node2 temp = table[hash];
		if(temp==null) {
			return null;
		}else {
			while(temp!=null) {
				if (temp.getKey().equals(key)) {
					return temp.getValue();
				}
				temp = temp.getNext();
				
			}
			return null;
		}
		

	}
	public void put(Object key, Object value) {
		
		//定义一个新的节点
		Node2 newNode = new Node2();
		newNode.setHash(myHash(key, table.length));
		newNode.setKey(key);
		newNode.setValue(value);
		newNode.setNext(null);
		
		//判断是否为null,来存放值
		if(table[newNode.getHash()]==null) {
			//直接放置就可以
			table[newNode.getHash()]=newNode;
		}else {
			//创建一个临时的节点
			Node2 temp = table[newNode.getHash()];
			Node2 temp1 = temp.getNext();
			while (temp1!=null) {
				if (temp1.getKey().equals(newNode.getKey())) {
					temp1.setValue(newNode.getValue());
					replaceKey = true;
					break;
				}else {
					temp = temp1;
					temp1 = temp.getNext();
				}
				if(replaceKey==false) {
					temp.setNext(newNode);	
				}
			}	
		}
		replaceKey = false;
	}
	public int myHash(Object key1,int length) {
		//一般有两种的方法可以进行选着,
		//一种是进行位运算,另一种是取余,前一种运算效率高,后一种运算效率低
		return (int)key1&(length-1);
	}

3、想要继续添加方法的话,可以继续王里面添加,可以对比以往的代码进行写,也可以对比着源代码进行写



二、ThreeMap

底层

先看一下如何建立Map结构对象的

private transient Entry<K,V> root;

这个Entry和Node(HashMap)是一样的,让我们打开源码的Entry来看一下

static final class Entry<K,V> implements Map.Entry<K,V> {
        K key;
        V value;
        Entry<K,V> left;
        Entry<K,V> right;
        Entry<K,V> parent;
        boolean color = BLACK;

        Entry(K key, V value, Entry<K,V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }
        public K getKey() {
            return key;
        }
        public V getValue() {
            return value;
        }
        public V setValue(V value) {
            V oldValue = this.value;
            this.value = value;
            return oldValue;
        }
        public boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;

            return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
        }

        public int hashCode() {
            int keyHash = (key==null ? 0 : key.hashCode());
            int valueHash = (value==null ? 0 : value.hashCode());
            return keyHash ^ valueHash;
        }

        public String toString() {
            return key + "=" + value;
        }
    }
   

从这段代码的开头我们可以知道,Treemap是没有数组+链表的结构的,而是类似于LinkedList的结构,并且我们还是知道treeMap的最大的特点是排序的功能,所以,我们可以看得到:

 static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; Type[] ts, as; ParameterizedType p;
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {
                for (Type t : ts) {
                    if ((t instanceof ParameterizedType) &&
                        ((p = (ParameterizedType) t).getRawType() ==
                         Comparable.class) &&
                        (as = p.getActualTypeArguments()) != null &&
                        as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }

如果太复杂的话啊我们可一写出来简单一点的

public class myTreemap1 {
	public static void main(String[] args) {
		Map<Integer, String> aa = new TreeMap<Integer, String>();
		aa.put(11, "asfsaf");
		aa.put(14, "asfsaf");
		aa.put(15, "asfsaf");
		aa.put(13, "asfsaf");
		aa.put(12, "asfsaf");
		System.out.println(aa);//添加的时候是自动排序的
		Emp aaa1 = new Emp(1, "王", 21); 
		Emp aaa2 = new Emp(2, "李", 24); 
		Emp aaa3 = new Emp(3, "张", 23); 
		Emp aaa4 = new Emp(4, "宋", 24); 
		Map<Emp, String> aa2 = new TreeMap<Emp, String>();
		
	}
}

class Emp implements Comparable<Emp>{

	Integer number;
	String name;
	Integer age;
	
	
	
	public Emp(Integer a, String st, Integer ss) {
		super();
		this.number = a;
		this.name = st;
		this.age = ss;
	}



	@Override
	public int compareTo(Emp o) {
		if(this.age>o.age) {
			return 1;
		}else if(this.age<o.age) {
			return -1;
		}else {
			if(this.number>o.number) {
				return 1;
				
			}else if(this.number<o.number) {
				return -1;
			}else {
				return 0;
			}
		}
		
	}
	
}

可以找我的源代码进行观看,不过和这个博客写的是一样

github

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值