Java中Map的其他类型(WeakHashMap-IdentityHashMap-EnumMap)

来源:互联网 发布:指南针炒股软件好吗 编辑:程序博客网 时间:2024/05/19 22:25

一丶引用分类(面试


强引用:StongReference:引用指向对象,gc(Garbage collection)运行时不回收
软引用:SoftReference gc运行时可能回收(jvm内存不够)
弱引用:WealReference gc运行时立即回收
虚引用:PhantomReference 类似于无引用,主要跟踪对象被目收的状态,不能单独使用,必须与引用队列(ReferenceQueue) 联合使用


二、三个Map接口实现类

1.WeakHashMap:键为弱引用
2.ldentityHashMap:健比较地址去重,注意常量池的对象

3.EnumMap救举map,要 求键为枚举的值

package Others;import java.util.WeakHashMap;/*** * WeakHashMap键为弱类型 * gc运行立即被回收 *  * @author zw * */public class WeakHashMapDemo {public static void main(String[] args){WeakHashMap<String,String> whs = new WeakHashMap<String,String>();//常量池对象不会被回收whs.put("zzz", "zzz");whs.put("xxx", "xxx");//gc运行已被回收whs.put(new String("a"), "c");whs.put(new String("sssss"), "csdasd");System.gc();System.runFinalization();System.out.println(whs.size());}}

package Others;import java.util.IdentityHashMap;/*** * IdentityHashMap 键比较地址去重 * @author zw * */public class IdentityHashMapDemo {public static void main(String[] args){IdentityHashMap<String,String> it = new IdentityHashMap<String,String>();//常量池找那个的"a"it.put("a", "good");it.put("a","best");System.out.println(it.size());}}


package Others;import java.util.EnumMap;/*** * EnumMap * 要求键为枚举 * @author zw * */public class EnumMapDemo {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;}



阅读全文
0 0