This article analyzes the object residency of Android imitation String. Share it for your reference, as follows:
String a = "abc";
String b = "abc";
a == b true;
Variable a and variable b are the same value. This does not just mean that the values of the two are the same, but that they are the same string object. In Java's words, the result of a==b is true. However, this is only valid for strings and small integers or long integers. Other objects will not be resided, that is, if you create two objects and their values are equal, but they are not the same object. This problem is sometimes annoying, especially when you fetch an object from a persistent storage. If you take the same object twice, of course you want to finally take out the same object, but in fact you take out two copies. In other words, what you actually want is to fetch the same copy of the object in the storage in memory. Some storage layers will do this. For example, the implementation of JPA follows this pattern, and in other cases, you may have to do caching yourself.
How to make your object look like the string above; use the following class
import ; import ; class WeakPool<T> { private final WeakHashMap<T, WeakReference<T>> pool = new WeakHashMap<T, WeakReference<T>>(); public T get(T object) { final T res; WeakReference<T> ref = (object); if (ref != null) { res = (); } else { res = null; } return res; } public void put(T object) { (object, new WeakReference<T>(object)); } }
I hope this article will be helpful to everyone's Android programming design.