Java之Map实现升级版

package learn.java.cn.collection;

import java.util.LinkedList;

/*
 * 思路:数组中放list,list中放DefMap,即数组加链表;
 * 存放时,key的hashcode值 对数组长度求余后作为索引值 存放到数组中,
 * 这样在,取对应的value值时,只需求出参数key的hashcode值 ,不须遍历数组
 * 因为可能会遇到相通的余数,此时将它们放到同一list 
 */
public class UpMap
{
	int size;
	LinkedList[] arraylist=new LinkedList[999];
	
	
	public void put (Object key,Object value)
	{	System.out.println(key.hashCode());
		int index=key.hashCode()%arraylist.length;
		System.out.println(index);
		//arraylist[index]表示存入的 是DefMap 类型的列表
		//java.lang.NullPointerException
		//先判断是否是空链表
		if(arraylist[index]==null)
		{
			LinkedList list=new LinkedList();
			arraylist[index]=list;
			list.add(new DefMap(key,value));
			//指向同一对象,可以先赋值 后初始化;
			
		}
		arraylist[index].add(new DefMap(key,value));
	}
	
	
	public Object get(Object key)
	{	int i;
		int index=key.hashCode()%arraylist.length;
		
		

		for ( i=0;i<arraylist[index].size();i++)
		{
//			if (arraylist[index][i].key.equals(key))
//				
//				return arraylist[index][i].value;
//			error:The type of the expression must be an array type but it resolved to LinkedList
			
			//DefMap defmap=arraylist[index].get(i);
			/*
			 * error:Type mismatch: cannot convert from Object to DefMap
			 * 列表中的类型虽然是DefMap(object的子类),但list.get()方法得到的
			 * 是OBJect方法,不能由下自动转化为上,即不能子类引用指向父类对象
			 */
			DefMap defmap=(DefMap)(arraylist[index].get(i));
			
			if(defmap.key.equals(key))
				return( (DefMap)(arraylist[index].get(i))).value;
		}
		return null;
	}




	public static void main(String args[])
	{
		UpMap testMap=new UpMap();
		testMap.put("王尚权","小静");
		testMap.put("李白", "杨幂");
		System.out.println(testMap.get("王尚权"));
		
	
	
	}
}


class DefMap
{
	Object key;
	Object value;
	
	public DefMap(Object key,Object value)
	{
		this.key=key;
		this.value=value;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_38662930/article/details/84139238
今日推荐