2016-12-30 22:22:39 -08:00
|
|
|
// collectiontopics/CanonicalMapping.java
|
2020-10-07 13:35:40 -06:00
|
|
|
// (c)2020 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.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com 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;
|
2017-05-01 14:33:10 -06:00
|
|
|
Element(String id) { ident = id; }
|
2015-06-15 17:47:35 -07:00
|
|
|
@Override
|
|
|
|
public String toString() { return ident; }
|
|
|
|
@Override
|
2017-01-10 14:11:16 -08:00
|
|
|
public int hashCode() {
|
|
|
|
return Objects.hashCode(ident);
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
@Override
|
|
|
|
public boolean equals(Object r) {
|
|
|
|
return r instanceof Element &&
|
2017-01-08 22:55:49 -08:00
|
|
|
Objects.equals(ident, ((Element)r).ident);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2020-10-07 17:06:42 -06:00
|
|
|
@SuppressWarnings("deprecation")
|
2015-06-15 17:47:35 -07:00
|
|
|
@Override
|
|
|
|
protected void finalize() {
|
|
|
|
System.out.println("Finalizing " +
|
|
|
|
getClass().getSimpleName() + " " + ident);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Key extends Element {
|
2017-05-01 14:33:10 -06:00
|
|
|
Key(String id) { super(id); }
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
class Value extends Element {
|
2017-05-01 14:33:10 -06:00
|
|
|
Value(String id) { super(id); }
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
public class CanonicalMapping {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
int size = 1000;
|
|
|
|
// Or, choose size via the command line:
|
|
|
|
if(args.length > 0)
|
2017-05-01 17:43:21 -06:00
|
|
|
size = Integer.valueOf(args[0]);
|
2015-06-15 17:47:35 -07:00
|
|
|
Key[] keys = new Key[size];
|
2017-01-22 16:48:11 -08:00
|
|
|
WeakHashMap<Key,Value> map =
|
|
|
|
new WeakHashMap<>();
|
2015-06-15 17:47:35 -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();
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|