Citation classification

One, reference
1. Strong reference: StrongReference refers to the object, which is not recycled when gc runs.
2. Soft reference: SoftReference, may be reclaimed during gc runtime (when jvm memory is not enough).
3. Weak reference: WeakReference, which is recycled immediately when gc runs.
4. Phantom reference: PhauntomReference, similar to no reference, is mainly used to track the status of the object being recycled. It cannot be used alone and must be used in conjunction with the reference queue (ReferenceQueue).
Second, the map interface implementation class
1.WeakHashMap: the key is a weak reference.
2.IdentityHashMap: Compare key values ​​to the same. (Go to the constant pool)
3.EnumMap: require the key to be the enumeration value
import java.util.WeakHashMap;

/**
*WeakReference
* Hash table based Map implemented with weak keys.
* pair key—"weak
* recycle using 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());        
}

}
result: 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());
}

}
result: 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());
}

}
//enumeration
enum enump {
SPRING,SUMMER,AUTUMN,WINTER
}

Result: 4

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325860430&siteId=291194637