一,引用
1.强引用:StrongReference引用指向对象,gc运行时不回收。
2.软引用:SoftReference,gc运行时可能回收(jvm内存不够时)。
3.弱引用:WeakReference,gc运行时立即回收。
4.虚引用:PhauntomReference,类似于无引用,主要用于跟踪对象被回收的状态,不能单独使用,必须与引用队列(ReferenceQueue)联合使用。
二, map接口实现类
1.WeakHashMap:键为弱引用。
2.IdentityHashMap:比较键值去雷同。(去的是常量池中的)
3.EnumMap:要求键为枚举值
import java.util.WeakHashMap;
/**
* 弱引用
* 以弱键 实现的基于哈希表的 Map。
* 对键—》弱
* 使用gc回收
* @author
*
*/
public class WeakHashMap_text {
public static void main(String[] args) {
WeakHashMap<String, String> weakHashMap=new WeakHashMap<String,String>();
//常量池不会被回收
weakHashMap.put("a", "siber");
weakHashMap.put("b","master");
//非常量池会被回收
weakHashMap.put(new String("sd"), "archer");
System.gc();//运行垃圾回收器
System.runFinalization();// 运行处于挂起终止状态的所有对象的终止方法
System.out.println(weakHashMap.size());
}
}
结果:2
package map;
import java.util.IdentityHashMap;
/**
*
* @author Lenovo
*
*/
public class IdentityHashMap_text {
public static void main(String[] args) {
IdentityHashMap<String, String> map=new IdentityHashMap<String,String>();
//常量池
map.put("a","siber");
map.put("a","archer");
map.put(new String("b"), "winter");
map.put(new String("b"), "win");
System.out.println(map.size());
}
}
结果:3
package map;
import java.util.EnumMap;
/**
*
* @author Lenovo
*
*/
public class EnumMap_text {
public static void main(String[] args) {
EnumMap<enump,String> map=new EnumMap<enump,String>(enump.class);
map.put(enump.SPRING, "siber");
map.put(enump.SUMMER, "siber");
map.put(enump.AUTUMN, "siber");
map.put(enump.WINTER, "siber");
System.out.println(map.size());
}
}
//枚举
enum enump {
SPRING,SUMMER,AUTUMN,WINTER
}
结果:4