53 lines
1.4 KiB
Java
Raw Normal View History

2016-08-02 11:52:46 -06:00
// understandingcollections/CanonicalMapping.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// Demonstrates WeakHashMap
2015-06-15 17:47:35 -07:00
import java.util.*;
class Element {
private String ident;
public Element(String id) { ident = id; }
@Override
public String toString() { return ident; }
@Override
public int hashCode() { return ident.hashCode(); }
@Override
public boolean equals(Object r) {
return r instanceof Element &&
ident.equals(((Element)r).ident);
}
@Override
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];
WeakHashMap<Key,Value> map = new WeakHashMap<>();
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();
}
2015-09-07 11:44:36 -06:00
}