-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathWeakReference_example.java
57 lines (48 loc) · 1.29 KB
/
WeakReference_example.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.WeakHashMap;
public class WeakReference_example {
/**
* Âûâîä
* WeakReference - îáåðòêà äëÿ îáúåêòà, êîòîðûé áóäåò î÷èùåí ïîñëå çàïóñêà GC
* HashWeakReference - êîíòåéíåð äëÿ îáúåêòîâ-êëþ÷åé è îáúåêòîâ-çíà÷åíèé
* ( òàê æå áóäåò î÷èùåí ïîñëå çàïóñêà GC )
*/
public static void main(String[] args){
System.out.println("begin");
WeakReference<Value> ref=new WeakReference<Value>(new Value("first"));
WeakHashMap<Key, Value> map=new WeakHashMap<Key,Value>();
map.put(new Key("1"), new Value("first"));
map.put(new Key("2"), new Value("second"));
map.put(new Key("3"), new Value("third"));
map.put(new Key("4"), new Value("fourth"));
// System.gc();
System.out.println("Value:"+ref.get());
Iterator<Key> iterator=map.keySet().iterator();
while(iterator.hasNext()){
Key key=iterator.next();
System.out.println(key+" "+key.hashCode()+" "+map.get(key));
}
System.out.println("-end-");
}
}
class Key{
private String key;
public Key(String key){
this.key=key;
}
@Override
public String toString() {
return key;
}
}
class Value{
private String value;
public Value(String value){
this.value=value;
}
@Override
public String toString() {
return this.value;
}
}