OnJava8-Examples/collectiontopics/CanonicalMapping.java

53 lines
1.4 KiB
Java
Raw Normal View History

2016-12-30 22:22:39 -08:00
// collectiontopics/CanonicalMapping.java
// (c)2021 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; }
@Override public String toString() { return ident; }
@Override public int hashCode() {
2017-01-10 14:11:16 -08:00
return Objects.hashCode(ident);
}
@Override public boolean equals(Object r) {
2015-06-15 17:47:35 -07:00
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")
@Override protected void finalize() {
2015-06-15 17:47:35 -07:00
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
}