基于散列表hashcode实现简单SimpleMap_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 基于散列表hashcode实现简单SimpleMap

基于散列表hashcode实现简单SimpleMap

 2011/10/10 8:06:09  jsczxy2  http://jsczxy2.iteye.com  我要评论(0)
  • 摘要:packagecom.test;importjava.util.LinkedList;importjava.util.ListIterator;publicclassSimpleMap{privatestaticfinalintSZ=997;privateLinkedList[]ls=newLinkedList[SZ];publicObjectput(Objectkey,Objectvalue){Objectresult=null;intindex=key.hashCode()%SZ;if
  • 标签:has 实现 Map Hash

package com.test;

import java.util.LinkedList;
import java.util.ListIterator;

public class SimpleMap {
	private static final int SZ = 997;

	private LinkedList[] ls = new LinkedList[SZ];
	
	public Object put(Object key,Object value){
		Object result = null;
		int index = key.hashCode() % SZ;
		if(index < 0) index = -index;
		if(ls[index] == null)
			ls[index] = new LinkedList();
		LinkedList l = ls[index];
		MapObj mapObj = new MapObj(key,value);
		ListIterator it = l.listIterator();
		boolean found = false;
		while(it.hasNext()){
			Object o = it.next();
			if(mapObj.equals(o)){
				result = ((MapObj)o).getValue();
				it.set(mapObj);
				found = true;
				break;
			}
		}
		if(!found){
			ls[index].add(mapObj);
		}
		return result;
	}
	
	public Object get(Object key){
		int index = key.hashCode() % SZ;
		if(index < 0) index = -index;
		if(ls[index] == null)
			return null;
		LinkedList l = ls[index];
		MapObj mapObj = new MapObj(key, null);
		ListIterator it = l.listIterator();
		while(it.hasNext()){
			Object o = it.next();
			if(mapObj.equals(o)){
				return ((MapObj)o).getValue();
			}
		}
		return null;
	}
	
	
	class MapObj {
		Object key;
		Object value;
		
		public MapObj(Object key,Object value){
			this.key = key;
			this.value = value;
		}

		public Object getKey() {
			return key;
		}

		public void setKey(Object key) {
			this.key = key;
		}

		public Object getValue() {
			return value;
		}

		public void setValue(Object value) {
			this.value = value;
		}

		public boolean equals(Object obj) {
			return key.equals(((MapObj)obj).key);
		}
		
	}

	
	
}
?
发表评论
用户名: 匿名