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