引用分类
- 强引用 StrongReference:引用指向对象,gc(Garbage collection)运行时不回收
- 软引用 SoftReference :gc运行时可能回收(jvm内存不够)
- 弱引用 WeakReference:gc运行时立即回收
- 虚引用 PhantomReference:类似于无引用,主要跟踪对象被回收的状态,不能单独使用,必须与引用队列(ReferenceQueue)联合使用。
目的:避免对象长期驻留在内存中,解决垃圾回收机制回收时机问题
三个Map接口实现类
1. WeakHashMap :键为弱引用
package com.bjsxt.others.three;
import java.util.WeakHashMap;
/**
* WeakHashMap 键为弱类型,gc运行立即回收
* @author Administrator
*
*/
public class WeakHashMapDemo {
/**
* @param args
*/
public static void main(String[] args) {
WeakHashMap<String,String> map =new WeakHashMap<String,String>();
//测试数据
//常量池对象,不会回收
map.put("abc", "a");
map.put("d", "test");
//gc运行 已被回收
map.put(new String("bjsxt"), "c");
map.put(new String("dsf"), "d");
//通知回收
System.gc();
System.runFinalization();
System.out.println(map.size());
}
}
2. IdentityHashMap:键比较地址去重,注意常量池的对象
package com.bjsxt.others.three;
import java.util.IdentityHashMap;
/**
* IdentityHashMap 键比较地址去重
* @author Administrator
*
*/
public class IdentityHashMapDemo {
/**
* @param args
*/
public static void main(String[] args) {
IdentityHashMap<String ,String> map =new IdentityHashMap<String,String>();
//常量池中的"a"
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());
}
}
3. EnumMap:枚举map,要求键为枚举的值
package com.bjsxt.others.three;
import java.util.EnumMap;
/**
* EnumMap要求键为枚举
* @author Administrator
*
*/
public class EnumMapDemo {
/**
* @param args
*/
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
}