package gcmap;public class Element {private String ident;public Element(String id) {ident = id;}@Overridepublic String toString() {return ident;}@Overridepublic int hashCode() {return ident.hashCode();}@Overridepublic boolean equals(Object r) {return r instanceof Element && ident.equals(((Element) r).ident);}@Overrideprotected void finalize() throws Throwable {System.out.println("Finalizing "+getClass().getSimpleName()+" "+ident);}}
package gcmap;public class Key extends Element{public Key(String id) {super(id);}}
package gcmap;public class Value extends Element{public Value(String id) {super(id);}}
package gcmap;import java.util.Set;import java.util.WeakHashMap;public class CannonicalMapping {public static void main(String[] args) {int size=10;if(args.length>0){size=new Integer(args[0]);}Key[] keys=new Key[size];WeakHashMap<Key, Value> map=new WeakHashMap<Key, Value>();for(int i=0;i<size;i++){Key k=new Key(Integer.toString(i));Value v=new Value(Integer.toString(i));if(i%3==0){keys[i]=k;}map.put(k, v);}System.gc();try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}Set<Key> _keys=map.keySet();for(Key key:_keys){System.out.println("key :"+key+";value :"+map.get(key));}}}
輸出結果:
Finalizing Key 8
Finalizing Key 7
Finalizing Key 5
Finalizing Key 4
Finalizing Key 2
Finalizing Key 1
`````````````````````````````````key :9;value :9
`````````````````````````````````key :6;value :6
`````````````````````````````````key :0;value :0
`````````````````````````````````key :3;value :3