其实我是不能说很了解hash的,我只是把它当做数组与链表的结合,数组为主,链表在数组上,我按我的理解把它实现出来,它的形式就是一个一定长度的数组加上n条链表。
首先我先简单介绍一下我所知道哈希链表:
哈希表是基于数组的,用于存储大批量的数据;如果说数组是查找数据的能手,链表是
增删数据的能手,那么哈希表便是奉行的我们中国的“中庸之道”。他可以说是数组与链表的结合。
如果你不追求完美的话,只想着体验一下哈希表,那么建立一个哈希表其实很简单:你只需要一个节点类和一个方法类就可以。
一下是节点类:
public class Student { //声明学生的属性 private String name ; private int namber ; private Student stuNext ; /** * 构造方法 * @param name */ public Student(String name,int namber){ this.name = name ; this.namber = namber ; } public void setName(String name){ this.name = name ; } public String getName(){ return name ; } public void setNamber(int namber){ this.namber = namber; } public int getNumber(){ return namber ; } public void setStu(Student stuNext){ this.stuNext = stuNext ; } public Student getStu(){ return stuNext; } }
其实方法类也就是包括最基本的增删改查的类,理想情况下 ,用递归方法比较好,但是由于我当时没有想到如何用递归方法所以我采用的是其他方法。
这里我只展示其中一部分代码(增,查)
其中方法可以根据个人的想法来写并没有固定模式,这里我用的是取余法。
/** * 添加student的方法 */ public void add(Student stu) { int key = stu.getNumber(); int index = key % 7; if (hashline[index] == null) { hashline[index] = stu; //System.out.println("hashline[index]=" + hashline[index].getName()); } else if (hashline[index] != null) { Student stu1 = this.getFinal(hashline[index]); System.out.println("stu111"+stu1); stu1.setStu(stu); System.out.println("stu1=" + stu1.getStu().getName()); } // }
/** * 查找的方法 */ public Student find(int key) { int index = key % 7; if(hashline[index]==null){ System.out.println("没有此人!"); return null; } Student stu = hashline[index]; int i = 0; if (this.getlenght(stu) == 0) { System.out.println("没有此人"); return null; } while (i != this.getlenght(stu)) { if (stu == null) { System.out.println("没有此人"); return null; } else if (stu != null) { if (stu.getNumber() == key) { return stu; } else { stu = hashline[index]; } } i++; System.out.println("i=" + i); } return null; }
特别提示:用递归方法比较好,这个方法一不注意就有可能报空。里面有一些嵌套的方法没有给出。
测试:
public static void main(String[] args) { HashLine hf = new HashLine(); // Student stu1 = new Student("张三", 01); Student stu2 = new Student("里斯", 02); Student stu13 = new Student("王五", 05); Student stu3 = new Student("liuzi", 8); Student stu4 = new Student("起", 9); Student stu5 = new Student("吧", 11); Student stu6 = new Student("就", 15); hf.add(stu13); hf.add(stu2); hf.add(stu1); hf.add(stu3); hf.add(stu6); hf.add(stu4); hf.add(stu5); System.out.println("找到此人 " + hf.find(01).getName()); hf.find(13); }
输出结果为:找到此人张三
没有此人