HashMap

package test;

import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;

public class HashMap<K, V> {

	Node<K, V>[] table;//链表数组  存储结构

	@SuppressWarnings("unchecked")
	public HashMap() {
		table = new Node[10];
	}

	//根据key计算数组下标  如果数组该下标已存在元素 则改为存该元素  并将该元素的next指向原元素
	public Node<K, V> put(K key, V value) {
		Node<K, V> node;
		if ((node = this.getNode(key)) != null) {
			node.value = value;
		} else {
			Node<K, V> newNode = new Node<K, V>(key, value);
			node = table[hash(key)];
			newNode.next = node;
			table[hash(key)] = newNode;
			node = newNode;
		}

		return node;
	}

	//根据key计算数组下标 再遍历链表找到相应的key对应的value
	public Node<K, V> getNode(K key) {

		Node<K, V> node = this.table[hash(key)];

		if (node != null) {
			if (node.key.equals(key)) {
				return node;
			} else {
				while ((node = node.next) != null) {
					if (node.key.equals(key)) {
						return node;
					}
				}
			}
		}

		return node;
	}

	public V get(K key) {

		Node<K, V> node = this.getNode(key);

		return node == null ? null : node.value;
	}

	public int hash(K key) {
		int hashcode = key.hashCode() % 10;
		return hashcode;
	}
	
	//链表节点内部类
	@SuppressWarnings("hiding")
	class Node<K, V> {
		Node<K, V> next;
		K key;
		V value;

		public Node(K key, V value) {
			// System.out.println("hash node ...");
			this.key = key;
			this.value = value;
		}
	}

	//key set 内部类 维护key值
	final class HashMapKeySet extends AbstractSet<K> {
		public final Iterator<K> iterator() {
			return new HashMapKeyIterator();
		}

		@Override
		public int size() {
			// TODO Auto-generated method stub
			return 0;
		}
	}

	
	//实际管理key值得迭代器 按数组下标顺序遍历节点
	final class HashMapKeyIterator implements Iterator<K> {

		private int index = 0;

		private Node<K, V> node = null;

		@Override
		public boolean hasNext() {

			if (node != null) {

				node = node.next;

				while (node == null && index < table.length - 1) {
					index++;
					node = table[index];
				}

			} else {
				node = table[index];
				while (node == null && index < table.length - 1) {
					index++;
					node = table[index];
				}
			}

			return node != null;
		}

		@Override
		public K next() {
			return node.key;
		}

	}

	public Set<K> keySet() {
		return new HashMapKeySet();
	}

	public static void main(String args[]) {
		HashMap<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < 100; i++) {
			map.put(i + "", "a");
		}

		for (String key : map.keySet()) {
			System.out.println(key + "==>" + map.get(key));
		}

		System.out.println("##################");

		map.put("1", "c");
		map.put("4", "d");

		for (String key : map.keySet()) {
			System.out.println(key + "==>" + map.get(key));
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值