In Android development, the efficient data structure replaces HashMap with SparseArray, and sparsearrayhashmap

Source: Internet
Author: User

In Android development, the efficient data structure replaces HashMap with SparseArray, and sparsearrayhashmap

#### Efficient data structure in Android Development
In android development, data structures commonly used in java2ee or android include Map, List, and Set. However, android, as a mobile platform, is obviously not ideal for Some APIs (many of which are efficiency problems, in the spirit of building better wheels, the android Team compiled their own APIs to replace java APIs

1. SimpleArrayMap <K, V> and ArrayMap <K, V>

In essence, ArrayMap inherits from SimpleArrayMap. It is mainly used to implement api methods like HashMap, so that developers who are used to using HashMap do not feel any difference. In essence, it is the re-encapsulation of SimpleArrayMap + Map.

Generally, these two classes are used to replace HashMap, because they are more efficient than HashMap, and the memory is also optimized.

2. SparseArray <T> and SparseArrayCompat <T> and LongSparseArray <T>

Among the three classes, the first two are basically the same class, except that the second class has the removeAt method and the third is the Long type.

These three classes are also used to replace HashMap, except that their key type is Integer or Long. In actual development, such as the ing of month abbreviations, or File Cache ing, viewHolder is particularly applicable

3. AtomicFile

AtomicFile is not used to replace File, but serves as an auxiliary class for File. AtomicFile is used to implement transactional atomic operations, that is, File read/write must be complete and is suitable for File read/write operations in multiple threads.

Secure Operations for reading and writing files in multiple threads

----
##### Replace HashMap with SparseArray
SparseArray is a tool class provided by android. It can be used to replace hashmap for object storage. It implements a matrix compression algorithm internally and is suitable for storing sparse matrices.

PS: the support package also provides a compatible class SparseArrayCompat, which is basically the same as SparseArray, except that the second class has the removeAt method.

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

I. Comparison with Hashmap

Since android recommends this feature, it is naturally useful. It implements internal compression algorithms and can perform matrix compression, which greatly reduces storage space and saves memory. In addition, its search algorithm is a binary method, which improves the search efficiency.

Replacement principle:

1>

If HashMap <Integer, E> hashMap = new HashMap <Integer, E> ();

It can be replaced by SparseArray <E> sparseArray = new SparseArray <E> ();

2>

If HashMap <Integer, Boolean> hashMap = new HashMap <Integer, Boolean> is used

It can be replaced by SparseBooleanArray array = new SparseBooleanArray ();

3>

If HashMap <Integer, Integer> hashMap = new HashMap <Integer, Integer> is used

It can be replaced by SparseIntArray array = new SparseIntArray ();

Ii. Usage

Since it is a key-value pair, there will be addition, deletion, modification, and query, but remember to first initialize:


Button btn = null; // test view, meaningless
Button btn02 = null; // test view, indicating the newly added object
Final int KEY = 1;

/*
* SparseArray refers to a Sparse array (Sparse
* Array), the so-called sparse array means that most of the content values in the array are not used (or both are zero), and only a few spaces in the array are used.
*. This results in a waste of memory space. To save memory space and do not affect the original content values in the array, we can use a compression method to represent the content of a sparse array.
*/
SparseArray <View> array = new SparseArray <View> ();


 

2.1 increase 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 modify data


/* Modify data */
// Before the put data operation, the system checks whether the data to be put already exists. If the data already exists, the system modifies the data and adds the data if the data 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 search for Data


/* Search for Data */
// Public E get (int key)
Array. get (KEY );
// Public E get (int key, E valueIfKeyNotFound)
// Get (int key) only calls get (int key, E valueIfKeyNotFound). The last one can be seen from the variable name of the passed parameter, the input value is the value returned when it cannot be found. get (int key) returns null by default when it cannot be found.
Array. get (KEY, btn); // if the key cannot find the value, the second parameter is returned. Same as default value


 

2.4 locate the key value


// View the keys at the specified position:
// Public int keyAt (int index)
Array. keyAt (1); // returns-1 if no value is found.


 

2.5 locate and find the value


// View the value at the specified position:
// Public E valueAt (int index)
Array. valueAt (1 );
// View the position of the value. If no value is found,-1 is returned:
// Public int indexOfValue (E value)
Array. indexOfValue (btn );



Iii. 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 1, January 19, 2015
*/
Public class MainActivity extends Activity {

@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );

Int maxMemory = (int) (fig. getRuntime (). maxMemory ()/1024 );
Log. d ("TAG", "Max memory is" + maxMemory + "KB ");


Button btn = null; // test view, meaningless
Button btn02 = null; // test view, indicating the newly added object
Final int KEY = 1;

/*
* SparseArray refers to a Sparse array (Sparse
* Array), the so-called sparse array means that most of the content values in the array are not used (or both are zero), and only a few spaces in the array are used.
*. This results in a waste of memory space. To save memory space and do not affect the original content values in the array, we can use a compression method to represent the content of a 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 );

/* Modify data */
// Before the put data operation, the system checks whether the data to be put already exists. If the data already exists, the system modifies the data and adds the data if the data 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 );

/* Search for Data */
// Public E get (int key)
Array. get (KEY );
// Public E get (int key, E valueIfKeyNotFound)
// Get (int key) only calls get (int key, E valueIfKeyNotFound). The last one can be seen from the variable name of the passed parameter, the input value is the value returned when it cannot be found. get (int key) returns null by default when it cannot be found.
Array. get (KEY, btn); // if the key cannot find the value, the second parameter is returned. Same as default value

// View the keys at the specified position:
// Public int keyAt (int index)
Array. keyAt (1); // returns-1 if no value is found.

// View the value at the specified position:
// Public E valueAt (int index)
Array. valueAt (1 );
// View the position of the value. If no value is found,-1 is returned:
// Public int indexOfValue (E value)
Array. indexOfValue (btn );

SparseBooleanArray d;
}
}


Test code 4:

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

@ Override
Public int getCount (){
Return mPages. size ();
}

@ Override
Public Fragment getItem (int position ){
Return getPagerItem (position). instantiate (mPages. getContext (), position );
}

@ Override
Public Object instantiateItem (ViewGroup container, int position ){
Object item = super. instantiateItem (container, position );
If (item instanceof Fragment ){
MHolder. put (position, new WeakReference <Fragment> (Fragment) item ));
}
Return item;
}

@ Override
Public void destroyItem (ViewGroup container, int position, Object object Object ){
MHolder. remove (position );
Super. destroyItem (container, position, object );
}

@ Override
Public CharSequence getPageTitle (int position ){
Return getPagerItem (position). getTitle ();
}

@ Override
Public 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 );
}

}

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.