package com.algorithm.charactor1;
import java.util.LinkedList;
/**
*本质是一个数组, 通过hash算法,指定到具体的数组下标 ,该下表下是一个链表,
分离链接。每个数组位置是一个链表。
*/
public class Hash {
//数组
private LinkedList<Student> [] array;
//多少个元素
private int currentSize;
private static int DEFAULTSIZE = 17;
//插入操作
public void insert(Student student){
Integer index = myHash(student);
LinkedList<Student> linkedList = array[index];
if (!linkedList.contains(student)) {
linkedList.add(student);
this.currentSize++;
}
if (currentSize+1 > array.length) {
//扩容操作
rehash();
}
}
private void rehash() {
LinkedList<Student> []newArray = new LinkedList[nextPrime(array.length)];
int i =0 ;
for (LinkedList<Student> linkedList : newArray) {//初始化新的链表数组
newArray[i++] = new LinkedList<Hash.Student>();
}
array = newArray;
currentSize = 0;
for (LinkedList<Student> linkedList : array) {//老的链表数组
for (Student student : linkedList) {
insert(student);//把老数组中的值,重新计算hash放到新的 数组中。
}
}
}
public void remove(Student student){
Integer index = myHash(student);
LinkedList<Student> linkedList = array[index];
if (!linkedList.contains(student)) {
return ;
}
linkedList.remove(student);
this.currentSize--;
}
public Boolean contains(Student student){
Integer index = myHash(student);
LinkedList<Student> linkedList = array[index];
return linkedList.contains(student);
}
public Hash() {
this(DEFAULTSIZE);
}
public Hash(int size) {
Integer nextPrime = nextPrime(size);
array = new LinkedList[nextPrime];
int index =0 ;
for (LinkedList<Student> linkedList : array) {
array[index++] = new LinkedList<Hash.Student>();
}
}
public Integer myHash(Student student){
int hashCode = student.hashCode();
int index = hashCode % array.length;
index = index < 0 ? index + array.length : index;
return index;
}
class Student{
String name;
int age;
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof Student && ((Student)obj).name.equals(this.name);
}
public Student(String name) {
super();
this.name = name;
}
}
//素数计算,网上抄的
public static Integer nextPrime(Integer begin){
int i;
int j;
for(i =begin;;i++){
boolean flag = true;
for(j=2;j<=i/2;j++){
if(i%j==0){
flag = false;
break;
}else if(i%j!=0){
continue;
}else{
break;
}
}
if(flag) {
return i;
}
}
}
public static void main(String[] args) {
Hash hash = new Hash(101);
hash.insert(hash.new Student("ll"));
for (LinkedList<Student> linkedList : hash.array) {
System.out.println(linkedList);
}
}
}
分离链接法 ,h存放数据
猜你喜欢
转载自blog.csdn.net/woyixinyiyi/article/details/79770650
今日推荐
周排行