hashset底层的数据结构是hash表,hash表实现方式采用数组+链表,数组类型为HashNode,每个数组元素为链表的头指针,链表中存储经过hash函数散列后冲突的元素,数组的长度为26
hashset存储的元素类型为字符串,取每个字符串的首字符的ascall码作为hash函数的输入,数组的长度为10,散列函数h(x)=x%10。
HashNode代码如下:
- public class HashNode {
- private String msg;
- private HashNode next;
- public String getMsg() {
- return msg;
- }
- public void setMsg(String msg) {
- this.msg = msg;
- }
- public HashNode getNext() {
- return next;
- }
- public void setNext(HashNode next) {
- this.next = next;
- }
- public HashNode(String msg, HashNode next) {
- this.msg = msg;
- this.next = next;
- }
- public HashNode() {
- }
- }
hashset实现如下:
- public class MyHashSet {
- private HashNode[] nodes = new HashNode[10];
- private int size = 0;
- public MyHashSet() {
- for (int i = 0; i < nodes.length; i++) {
- nodes[i] = new HashNode();
- }
- }
- public boolean add(String value) {
- if (contains(value)) { // 如果有这个元素,就不插入
- return false;
- }
- HashNode node = new HashNode(value, null);
- int index = (int) value.charAt(0) % nodes.length; // 取第一个字符作为hash函数的输入
- // 如果该链为空,直接插入,否则采用头插法
- if (nodes[index].getNext() == null) {
- nodes[index].setNext(node);
- } else {
- node.setNext(nodes[index].getNext());
- nodes[index].setNext(node);
- }
- size++;
- return true;
- }
- public boolean remove(String value) {
- if (!contains(value)) {
- return false;
- }
- int index = (int) value.charAt(0) % nodes.length;
- HashNode node = nodes[index];
- HashNode node2 = node.getNext();
- while (node2 != null) {
- if (node2.getMsg().equals(value)) {
- node.setNext(node2.getNext());
- size--;
- break;
- }
- node = node.getNext();
- node2 = node.getNext();
- }
- return true;
- }
- public void display() {
- for (int i = 0; i < nodes.length; i++) {
- HashNode node = nodes[i].getNext();
- System.out.print(i + " :");
- while (node != null) {
- System.out.print(node.getMsg() + " ");
- node = node.getNext();
- }
- System.out.println();
- }
- }
- public int size() {
- return size;
- }
- public boolean contains(String value) {
- int index = (int) value.charAt(0) % nodes.length;
- HashNode node = nodes[index].getNext();
- while (node != null) {
- if (node.getMsg().equals(value)) {
- return true;
- }
- node = node.getNext();
- }
- return false;
- }
- }
- public class TestMyHashSet {
- public static void main(String[] args) {
- MyHashSet myHashSet = new MyHashSet();
- myHashSet.add("hello");
- myHashSet.add("hey");
- myHashSet.add("apply");
- myHashSet.add("你好");
- myHashSet.add("你是谁");
- myHashSet.add("cat");
- myHashSet.add("dog");
- myHashSet.add("cat");
- myHashSet.add("你好");
- System.out.println("包含'你好'? " + myHashSet.contains("你好"));
- System.out.println("元素个数: " + myHashSet.size());
- myHashSet.display();
- myHashSet.remove("hello");
- System.out
- .println("*****************after remove 'hello'**********************");
- myHashSet.display();
- System.out.println("元素个数: " + myHashSet.size());
- }
- }
输出结果: