Android emulates String's object resident sample analysis

  • 2020-11-20 06:14:27
  • OfStack

An example of Android mimicking String is presented in this paper. To share for your reference, the details are as follows:

String a = "abc";

String b = "abc";

a == b true;

The variable a and the variable b have the same value. It's not just that they have the same value, it's the same string object. In Java's terms, a==b is true. However, this only works for strings and small or long integers. Other objects are not hosted, that is, if you create two objects whose values are the same, but they are not the same object. This problem is sometimes annoying, especially if you are fetching an object from a persistent store. If you take the same object twice, of course you want to end up with the same object, but you're actually taking out two copies. In other words, what you really want to pull out is the same copy of that object in memory that was in storage. Some storage layers do this. JPA, for example, follows this pattern. In other cases, you may have to do your own caching.

How do you make your objects look like string1 above? Use the following class


import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
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 = pool.get(object);
    if (ref != null) {
      res = ref.get();
    } else {
      res = null;
    }
    return res;
  }
  public void put(T object) {
    pool.put(object, new WeakReference<T>(object));
  }
}

I hope this article has been helpful for Android programming.


Related articles: