Efficient data structures in Android development replace HashMap with Sparsearray

Source: Internet
Author: User

Efficient data structures in Android development

Android development, in JAVA2EE or Android common data structure has map,list,set, but Android as a mobile platform, some API (many are efficiency issues) is obviously not ideal, in the spirit of making better wheels, The Android team has written its own API to replace the Java API

1, simplearraymap<k,v> and arraymap<k,v>

Essentially Arraymap inherited from Simplearraymap, mainly in order to implement a HashMap-like API method, so that the habit of using HashMap developers feel no difference, essentially simplearraymap+map re-encapsulation.

In general, these 2 classes are used primarily instead of hashmap because they are more efficient than hashmap and are optimized for memory.

2, Sparsearray and Sparsearraycompat and Longsparsearray

Of these 3 classes, the first 2 are basically the same class, except that the second class has a RemoveAt method, and the third is a long type.

These 3 classes are also used to replace HashMap, except that their key type is integer integer or long type, in real development, such as month abbreviation mapping, or file cache mapping, Viewholder is particularly suitable for

3, Atomicfile

Atomicfile first is not used instead of file, but as the auxiliary class of file from in, the function of Atomicfile is to implement the transactional atomic operation, that is, the file read and write must be complete, suitable for the file read and write operation in multi-threading.

Secure operation for file read and write in multi-threading

Replace HashMap with Sparsearray

Sparsearray is a tool class provided by Android, which can be used to replace HashMap for object storage, which implements a matrix compression algorithm, which is suitable for storing sparse matrices.

The Ps:support package also provides a compatible class Sparsearraycompat, both basic and Sparsearray are the same class, except that the second class has a RemoveAt method

Detailed analysis of the source code: http://stormzhang.com/android/2013/08/01/android-use-sparsearray-for-performance-optimization/

A comparison with HashMap

Since Android recommends using this thing, it's natural to use it for the truth. Its internal implementation of the compression algorithm, the matrix can be compressed, greatly reducing the storage space, saving memory. In addition, its search algorithm is dichotomy, which improves the efficiency of searching.

Replacement principle:

1>

If used: Hashmap<integer, e> HashMap = new Hashmap<integer, e> ();

Can be replaced by: sparsearray Sparsearray = new Sparsearray ();

2>

If used: Hashmap<integer, boolean> HashMap = new Hashmap<integer, boolean>

Can be replaced by: sparsebooleanarray array = new Sparsebooleanarray ();

3>

If used: Hashmap<integer, integer> HashMap = new Hashmap<integer, integer>

Can be replaced by: sparseintarray array = new Sparseintarray ();

Second, usage

Since it is a key value pair then there is an increase and deletion check, but remember to initialize first:

Button btn = null; Test view, meaningless    Button btn02 = null;//Test View, indicates new object    final int KEY = 1;    /     * * Sparsearray refers to a sparse array (Sparse * array) where the     so-called sparse array is the majority of the content values in the array are not used (or both 0), and only a small portion of the space in the array is used     *. Therefore, the memory space wasted, in order to save memory space, and do not affect the contents of the array of content values, we can use a compressed way to represent the contents of the sparse array.     */    sparsearray<view> array = new sparsearray<view> ();


2.1 Adding data

/* Add data *///public void put (int key, E value) {} array.put (key, BTN); public void append (int key, E value) {} array.append (key, BTN);

2.2 Modifying data

/*////////Before the put data, find out whether the data to put is already present, and if there is a modification, add it if it does not exist. public void put (int key, E value) array.put (key, BTN); public void setvalueat (int index, E value) array.setvalueat (KEY, BTN02);

2.3 Finding data

/* Find data *///public E get (int key) Array.get (key); Public E get (int key, E valueifkeynotfound)//Where get (int key) also just calls get (int key,e valueifkeynotfound), the last one from the parameter name of the argument can be seen, The value returned when it is not found. Get (int key) returns null by default when not found. Array.get (KEY, BTN); If this key cannot find value, then the second argument is returned. As with default value

2.4 By location, find the value of the key

View the keys for the first few positions://public int Keyat (int index) Array.keyat (1); If not found, return-1

2.5 through position, find value

View the values for the first few positions:    //public E valueat (int index)    array.valueat (1);    Check the location of the value, no words return-1:    //public int Indexofvalue (E value)    array.indexofvalue (BTN);


Third, the test code

Package Com.kale.pictest;import Android.app.activity;import Android.os.bundle;import android.util.log;import Android.util.sparsearray;import Android.util.sparsebooleanarray;import Android.view.view;import android.widget.button;/** * @author: * @description: * @web: http://stormzhang.com/android/2013/08/01/ android-use-sparsearray-for-performance-optimization/* @date: January 19, 2015 */public class Mainactivity extends Activity    {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Setcontentview (R.layout.activity_main);    int maxmemory = (int) (Runtime.getruntime (). MaxMemory ()/1024);    LOG.D ("TAG", "Max memory is" + MaxMemory + "KB"); Button btn = null; Test view, meaningless Button btn02 = null;    Test View, which represents the new object final int KEY = 1; /* * Sparsearray refers to a sparse array (Sparse * array) where the so-called sparse array is the majority of the content values in the array are not used (or both 0), and only a small portion of the space in the array is used *.     Therefore, the memory space wasted, in order to save memory space, and do not affect the contents of the array of content values, we can use a compressed way to represent the contents of the sparse array. */sparsearray<view> Array = new Sparsearray<view> ();    /* Add data *///public void put (int key, E value) {} array.put (key, BTN);    public void append (int key, E value) {} array.append (key, BTN);    /*////////Before the put data, find out whether the data to put is already present, and if there is a modification, add it if it does not exist.    public void put (int key, E value) array.put (key, BTN);    public void setvalueat (int index, E value) array.setvalueat (KEY, BTN02);    /* Find data *///public E get (int key) Array.get (key); Public E get (int key, E valueifkeynotfound)//Where get (int key) also just calls get (int key,e valueifkeynotfound), the last one from the parameter name of the argument can be seen,    The value returned when it is not found. Get (int key) returns null by default when not found. Array.get (KEY, BTN); If this key cannot find value, then the second argument is returned. Same as default value//View key for the first few positions://public int Keyat (int index) Array.keyat (1);    If not found, return-1//View the value of the number of positions://public E valueat (int index) array.valueat (1);    Check the location of the value, no words return-1://public int indexofvalue (E value) array.indexofvalue (BTN); Sparsebooleanarray D;}}


Test code four:

public class Fragmentpageritemadapter extends Fragmentpageradapter {private final Fragmentpageritems mpages;private Final sparsearraycompat<weakreference<fragment>> mholder;public Fragmentpageritemadapter (    Fragmentmanager FM, fragmentpageritems pages) {super (FM);    mpages = pages; Mholder = new Sparsearraycompat<> (Pages.size ());} @Overridepublic int GetCount () {return mpages.size ();} @Overridepublic Fragment getItem (int position) {return Getpageritem (position). Instantiate (Mpages.getcontext (), position);} @Overridepublic Object Instantiateitem (ViewGroup container, int position) {Object item = Super.instantiateitem (contain    er, position);    if (item instanceof Fragment) {mholder.put (position, New weakreference<fragment> ((Fragment) item)); } return item;    @Overridepublic void Destroyitem (ViewGroup container, int position, object object) {mholder.remove (position); Super.destroyitem (container, Position, object);} @Overridepublic CharSequence getpagetitle (int position) {return Getpageritem (position). GetTitle (); @Overridepublic float getpagewidth (int position) {return super.getpagewidth (position);}    Public Fragment getpage (int position) {final weakreference<fragment> Weakrefitem = mholder.get (position); Return (Weakrefitem! = null)? Weakrefitem.get (): null;} protected Fragmentpageritem getpageritem (int position) {return mpages.get (position);}}


Efficient data structures in Android development replace HashMap with Sparsearray

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.