Android Imitation string Object Hosting sample Analysis _android

Source: Internet
Author: User
Tags hosting

An example of this article analyzes the presence of an Android imitation string object. Share to everyone for your reference, specific as follows:

String a = "abc";

String B = "abc";

A = = b true;

Variable A and variable B are the same value. It's not just that the two values are the same, but that they are the same string object. In the case of Java, the result of A==b is true. However, this is only valid for strings and small integer or long integer types. Other objects are not hosted, meaning that if you create two objects and their values are equal, they are not the same object. This problem is sometimes annoying, especially when you take an object out of a persistent store. If the same object you have taken two of times, you certainly want to end up with the same object, but in fact you took out two copies. In other words, what you actually want is to take out the same copy of the object in memory in the store. Some storage tiers do this. For example, the implementation of JPA follows this pattern, and other situations may have to be cached by yourself.

How to make your object as if it were a string 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 will help you with the Android program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.