享元:實現Map容器,但是需要實現abstract類的內部方法;用來創建定製版的Map和Collection;
直接上源碼分析:
import java.util.*;
public class CountingMapData extendsAbstractMap<Integer,String>
{//主要實現method: entrySet()方法,實現的類:Entry此類繼承自Map.Entry<Integer,String>內部是一些Key和Value值的定義方法;
private int size;
private static String[]chars="A B C D E F G H I".split(" ");
CountingMapData(intsize){this.size=(size<0 ? 0 : size);}
private static classEntry implements Map.Entry<Integer,String>
{
int index;
Entry(intindex){this.index=index;}
public booleanequals(Object o){return Integer.valueOf(index).equals(o);}/*public booleanequals(Object o){return o instanceof Entry&&index==((Entry)o).index;}*/
public IntegergetKey(){return index;}
public StringgetValue(){returnchars[index%chars.length]+Integer.toString(index/chars.length);}
public StringsetValue(String value){throw new UnsupportedOperationException();}
public inthashCode(){return Integer.valueOf(index).hashCode();}
}
//按道理到這裏爲止CountingMapData就結束了(PS當然要算上下面的entrySet()方法),但爲了Map內部遍歷需要,實現了EntrySet類,此方法主要用以實現iterator()這個方法,其內部爲一個Iterator的匿名類,
class EntrySet extendsAbstractSet<Map.Entry<Integer,String>>
{
//private intsize;
//EntrySet(intsize){CountingMapData.this.size=(size<0 ? 0:(size>chars.length ?chars.length:size));}
public intsize(){return size;}
publicIterator<Map.Entry<Integer,String>> iterator()
{
return newIterator<Map.Entry<Integer,String>>()
{ private Entry entry=new Entry(-1);
publicboolean hasNext(){return entry.index<(size-1);}
publicMap.Entry<Integer,String> next(){entry.index++;return entry;}
publicvoid remove(){throw new UnsupportedOperationException();}
};
}
}
//如果你沒有編寫能遍歷的EntrySet類,那麼只能用for(;;)來手動添加入Map容器內部去,此處是一個Set容器來收集這些對象;
/*publicSet<Map.Entry<Integer,String>> entrySet()
{
Set<Map.Entry<Integer,String>>entries=new LinkedHashSet<Map.Entry<Integer,String>>();
for(inti=0;i<size;i++)
{
entries.add(newEntry(i));//手動添加
}
return entries;
}*/
/*
public static Map<Integer,String>select(final int index)
{
return newCountingMapData(index)
{
publicSet<Map.Entry<Integer,String>> entrySet(){
return new EntrySet(index);
}
};
}*/
Set<Map.Entry<Integer,String>>entrise=new EntrySet();
publicSet<Map.Entry<Integer,String>> entrySet()
{
return entrise;//返回的是一個Se<…>泛型類
}
public static voidmain(String[] args)
{
System.out.println(newCountingMapData(60));
}
}