实现Java hashmap

来源:互联网 发布:360提示网络连接失败 编辑:程序博客网 时间:2024/06/05 03:08
代码如下所示:
package com.myhashmap;public class TestMyHashMap {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubMyHashMap map = new MyHashMap();map.put(1, 1);map.put(2, 2);map.put(3, 3);map.put(4, 4);map.put(5, 5);map.put(1, 5);System.out.println(map.get(1));System.out.println(map.get(2));System.out.println(map.get(3));System.out.println(map.get(4));System.out.println(map.get(5));}}class Node{private int id;private int value;private Node next;public int hashcode(){return id;}public int getvalue(){return value;}public Node getNext(){return next;}public int getId() {return id;}public void setId(int id) {this.id = id;}public int getValue() {return value;}public void setValue(int value) {this.value = value;}public void setNext(Node next) {this.next = next;}}class MyHashMap{private  int initsize = 4;private double loadblance = 0.75;private int size;public Node[] nodes;public MyHashMap(){nodes = new Node[initsize];}public void put(int id,int value){Node node = new Node();node.setId(id);node.setValue(value);int hashcode = node.hashcode();hashcode = hashcode & (initsize-1);if(nodes[hashcode] == null){//如果数组没有值,则直接存储nodes[hashcode] = node;size++;//判断是否需要重新调整数组大小if(size > initsize*loadblance){//重新调整resize();}}else{Node tmp = nodes[hashcode];//先判断id对应的key是否已经存在while(tmp.getId() != id && tmp.getNext() != null){tmp = tmp.getNext();}if(tmp.getId() == id){tmp.setValue(value);return;}tmp.setNext(node);}}public int get(int key){Node node = new Node();node.setId(key);int hashcode = node.hashcode();hashcode = hashcode & (initsize-1);node = nodes[hashcode];while(node != null){if(node.getId() == key){return node.getvalue();}node = node.getNext();}return 0;}private void resize(){Node[] tmpnodes = new Node[initsize*2];for(int i=0; i < initsize;i++){Node tmp = nodes[i];//循环重组原数组的每一个元素while (tmp != null){int hashcode = tmp.hashcode();//获得在新数组中的位置hashcode = hashcode & (2*initsize-1);if(tmpnodes[hashcode] == null){//如果没有元素,则直接放入tmpnodes[hashcode] = tmp;}else{Node node = tmpnodes[hashcode];if(node.getNext() != null){node = node.getNext();}node.setNext(tmp);}tmp = tmp.getNext();}}initsize = initsize*2;nodes = tmpnodes;}}