package collection.others.Reference;
import java.lang.ref.WeakReference;
/**
* 引用分类:强、软、弱、虚
* 强与弱引用
*/
public class ReferenceDemo {
public static void main(String[] args) {
String str =new String("bjsxt is very good");
WeakReference<String> wr =new WeakReference<String>(str);
System.out.println("gc运行前:"+wr.get());
str =null;
System.gc();
System.runFinalization();
System.out.println("gc运行后:"+wr.get());
}
public static void testStrong(){
String str ="bjsxt is very good";
WeakReference<String> wr =new WeakReference<String>(str);
System.out.println("gc运行前:"+wr.get());
str =null;
System.gc();
System.runFinalization();
System.out.println("gc运行后:"+wr.get());
}
}
package collection.others.Reference;
import java.util.WeakHashMap;
/**
* WeakHashMap 键为弱类型,gc运行立即回收
*/
public class TestWeakHashMap {
public static void main(String[] args) {
WeakHashMap<String,String> map =new WeakHashMap<String,String>();
map.put("abc", "a");
map.put("d", "test");
map.put(new String("bjsxt"), "c");
map.put(new String("dsf"), "d");
System.gc();
System.runFinalization();
System.out.println(map.size());
}
}
package collection.others.Reference;
import java.util.IdentityHashMap;
/**
* IdentityHashMap 键比较地址去重
*/
public class TestIdentityHashMap {
public static void main(String[] args) {
IdentityHashMap<String ,String> map =new IdentityHashMap<String,String>();
map.put("a", "a1");
map.put("a", "a2");
System.out.println(map.size());
map.put(new String("a"), "a3");
map.put(new String("a"), "a4");
System.out.println(map.size());
}
}
package collection.others.Reference;
import java.util.EnumMap;
/**
* EnumMap要求键为枚举
*/
public class TestEnumMap {
public static void main(String[] args) {
EnumMap<Season,String> map =new EnumMap<Season,String>(Season.class);
map.put(Season.SPRING, "春困");
map.put(Season.SUMMER, "夏无力");
map.put(Season.AUTUMN, "秋乏");
map.put(Season.WINTER, "冬眠");
System.out.println(map.size());
}
}
enum Season{
SPRING,SUMMER,AUTUMN,WINTER
}