java学习笔记之WeakHashMap 、IdentityHashMap、EnumMap

1、WeakHashMap

其中的key是弱引用。(弱引用是指一旦GC运行,就会立刻回收,该引用所指的对象)
例子:

     /**
     * WeakHashMap 中的key为弱引用,GC(Garbage Collection)
     * 一旦运行就会立即回收
     * @author ly1
     *
     */
    public class TestWeakHashMap {
        public static void main(String[] args) {
            WeakHashMap whm = new WeakHashMap();
            whm.put("123", "123");
            whm.put("234", "123");
            whm.put(new String("hh"), "sf");
            whm.put(new String("hha"), "sf");

            System.gc();
            System.runFinalization();
            System.out.println(whm.size());
        }
    }

运行结果:

1
3

2、 IdentityHashMap

其中的key是以地址去重。
例子:

    import java.util.IdentityHashMap;
    import java.util.Map;

    /**
        * IdentityHashMap key以地址去重 
        * @author ly1
        *
    */
    public class TestIdentityHashMap {
        public static void main(String[] args) {
            Map map = new IdentityHashMap();
            map.put("1","1");
            map.put("1","1");

            //字符串中常量池中的字符串地址相等,所以重复
            System.out.println(map.size());

            map.put(new String("2"), "2");
            map.put(new String("2"), "2");

            //字符串对象地址不相等,所以不重复
            System.out.println(map.size());
        }
    }

运行结果:

1
3

3、EnumMap

其中key只能是枚举类型,将key限制在某个范围内。
例子:

import java.util.EnumMap;
import java.util.Map;

/**
 * EnumMap 其中key只能是一个枚举类型
 * @author ly1
 *
 */
public class TestEnumMap {
    /**
     * @param args
     */
    public static void main(String[] args) {
        Map<Season,String> map = new EnumMap<Season,String>(Season.class);
        map.put(Season.Spring, "spring");
        map.put(Season.Sunmmer, "summer");
        map.put(Season.Automn, "Automn");
        map.put(Season.Winter, "Winterx");

        System.out.println(map.size());
        System.out.println(map.size());
    }

}


enum Season{
    Spring, Sunmmer, Automn, Winter
}

运行结果:4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值