哈希也被称为散列,就是把任意长度的输入,通过散列算法,变换成固定长度的输出,这个输出值就是散列值。这里访问的时间复杂度为O(1).
现在假设数组array存放的是1到15这些数,现在要存的一个大小是7的Hash中,又该如何存储?我们存储的计算公式是 index = number % 7;
存储1到6的时候是这样的。位置都是一一对应的。
当没有对象指向ThreadLocal(key)时,该键位key为空时,value就会为空,调用方法时就会去清空该键位,让其他的键位进行存储。
2.链地址法(jdk8之后。 涉及到了链表,数组,红黑树)
将hash的每个单位作为链表的头节点,所有哈希地址为i的元素构成一个。这种处理方法的问题处理起来代价还是比较高的,CurrentHashMap就是中就使用了这种方式(保证了线程安全的前提下,效率又得到了保证),其中涉及到了元素尽量均匀,访问和操作速度要快,线程安全和扩容等问题。entry长度不能大于数组长度的75%,否则就会触发扩容机制进行扩容。
学会了一种新的方式来实现链表的创建,通过创建内部类的方式,其中利用了泛型的相关知识,通过创建链表的不同构造方法可以得到不同的实现方式,好像学到的更多了,逻辑能力不知道段没锻炼出来,但是调试打断点的能力倒是有所展现,每一步都是较为基础的,但一遍写出来还是挺难的。
public class LinkedQueue<E> {
//哨兵?虚拟头节点?哑节点?
private Node<E> head = new Node<>(null,null);
//定义一个节点类
static class Node<E>{
Node<E> next;
E value;
public Node(Node<E> next, E value) {
this.next = next;
this.value = value;
}
}
//链表实现队列的入队方法
public Node<E> push(E value){
Node<E> newNode = new Node<>(null, value);
Node<E> cur = head;
while (cur.next != null){
cur = cur.next;
}
cur.next = newNode;
return head.next;
}
//链表实现队列的出队方法
public boolean pop(){
if (head.next == null){
return false;
}
head.next = head.next.next;
return true;
}
//遍历方式
public void traverse(){
Node cur = head;
while (cur != null){
System.out.print(cur.value+" ");
cur = cur.next;
}
System.out.println("ff");
}
public static void main(String[] args) {
LinkedQueue<Object> linkedQueue = new LinkedQueue<>();
linkedQueue.push(1);
linkedQueue.push(2);
linkedQueue.push(3);
linkedQueue.traverse();
linkedQueue.pop();
linkedQueue. traverse();
}
}