2015-04-20 15:36:01 -07:00
|
|
|
|
//: containers/CanonicalMapping.java
|
2015-05-29 14:18:51 -07:00
|
|
|
|
// <20>2015 MindView LLC: see Copyright.txt
|
2015-04-20 15:36:01 -07:00
|
|
|
|
// Demonstrates WeakHashMap.
|
|
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
|
|
class Element {
|
|
|
|
|
private String ident;
|
|
|
|
|
public Element(String id) { ident = id; }
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public String toString() { return ident; }
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public int hashCode() { return ident.hashCode(); }
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public boolean equals(Object r) {
|
|
|
|
|
return r instanceof Element &&
|
|
|
|
|
ident.equals(((Element)r).ident);
|
|
|
|
|
}
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
|
protected void finalize() {
|
|
|
|
|
System.out.println("Finalizing " +
|
|
|
|
|
getClass().getSimpleName() + " " + ident);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class Key extends Element {
|
|
|
|
|
public Key(String id) { super(id); }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class Value extends Element {
|
|
|
|
|
public Value(String id) { super(id); }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class CanonicalMapping {
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
int size = 1000;
|
|
|
|
|
// Or, choose size via the command line:
|
|
|
|
|
if(args.length > 0)
|
|
|
|
|
size = new Integer(args[0]);
|
|
|
|
|
Key[] keys = new Key[size];
|
2015-05-05 11:20:13 -07:00
|
|
|
|
WeakHashMap<Key,Value> map = new WeakHashMap<>();
|
2015-04-20 15:36:01 -07:00
|
|
|
|
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; // Save as "real" references
|
|
|
|
|
map.put(k, v);
|
|
|
|
|
}
|
|
|
|
|
System.gc();
|
|
|
|
|
}
|
|
|
|
|
} /* (Execute to see output) *///:~
|