Map
map是有数组+链表实现的,代码如下:
public class MyMap {
LinkedList[] data;//链表
int size;
public MyMap(){
this(10);
}
public MyMap(int c){
data=new LinkedList[c];
}
public void put(Object key,Object value){
if(size+1>data.length){//扩容
LinkedList[] newArray=new LinkedList[size+(size>>1)];
System.arraycopy(data,0,newArray,0,size);
data=newArray;
}
MyEntry myEntry=new MyEntry(key,value);//Entry对象
int a=key.hashCode()%data.length;//取hash code值
a=a<0?-a:a;//如果是负数,取反
if(data[a]==null){//如果数组的这个位置是空的
LinkedList linked=new LinkedList();
data[a]=linked;//将链表放在数组的这个位置
linked.add(myEntry);//将entry放在链表中
}else{
LinkedList linkedList=data[a];//如果已有链表,将entry加入链表
for(int i=0;i<linkedList.size();i++){
MyEntry entry=(MyEntry)linkedList.get(i);
if(entry.key.equals(key)){//如果key重复,赋值value相同
entry.value=value;
}
}
data[a].add(myEntry);
}
}
public Object get(Object key){
int a=key.hashCode()%data.length;//对一个对象来说,它的hash码值相同
a=a<0?-a:a;
if(data[a]!=null){//从数组中的链表取出entry的value值
LinkedList list=data[a];
for(int i=0;i<list.size();i++){
MyEntry e=(MyEntry)list.get(i);
if(e.key.equals(key)){
return e.value;
}
}
}
return null;
}
public static void main(String[] args){
MyMap myMap=new MyMap(3);
myMap.put("zhang","ye");
myMap.put("feng","gou");
myMap.put("bai","yu");
myMap.put("guo","wei");
System.out.println(myMap.get("feng"));
System.out.println(myMap.get("guo"));
System.out.println(myMap.get("zhang"));
}
}
class MyEntry{
Object key;
Object value;
public MyEntry(Object key,Object value) {
this.key = key;
this.value=value;
}
}