package Practice;
import java.util.Iterator;
public class MyHashMap
{
int tableSize;
MyArrayList table;
public MyHashMap(int tableSize)
{
this.tableSize=tableSize;
table=new MyArrayList(this.tableSize);
for(int i=0;i<tableSize;i++)
table.add(new MyLinkedList());
}
public MyHashMap()
{
this(10);
}
public Object getValue(Object key)
{
int t=key.hashCode();
if(t<0)
t=0-t;
int ind=t%tableSize;
MyLinkedList tmp=(MyLinkedList)table.get(ind);
Iterator it=tmp.iterator();
while(it.hasNext())
{
MyPair curPair=(MyPair)it.next();
if(curPair.key.equals(key))
{
return curPair.value;
}
}
return null;
}
public void put(Object key,Object value)
{
int t=key.hashCode();
if(t<0)
t=0-t;
int index=t%tableSize;
MyLinkedList tmp=(MyLinkedList) table.get(index);
boolean found=false;
Iterator it=tmp.iterator();
while(it.hasNext())
{
MyPair curPair=(MyPair)it.next();
if(curPair.key.equals(key))
{
curPair.value=value;
found=true;
break;
}
}
if(found==false)
{
tmp.add(new MyPair(key,value));
}
}
}
class MyPair
{
public Object key;
public Object value;
public MyPair(Object key,Object value)
{
this.key=key;
this.value=value;
}
}
练习——HashMap
最新推荐文章于 2024-01-09 11:30:31 发布