Data structures for HashMap and Sparsearray in Java

Source: Internet
Author: User

Recently listening to colleagues said that the use of Sparsearray instead of HashMap can improve performance, so the edge of the two classes of data structure for a simple analysis.

Data structure of HashMap

HashMap is a combination of arrays and linked lists (in the data structure called "chain-Table hashing"), as shown in:


Photo Source: Java's HashMap and Hashtable

Data structure of Sparsearray

Sparsearray refers to a sparse array (Sparse array), in order to save memory space, and does not affect the value of the contents of the array. Inside there are two key members, Mkeys and Mvalues, each of which are arrays, as shown below:

view its put (int key, E value) as follows:

public void put (int key, E value) {    int i = Containerhelpers.binarysearch (Mkeys, msize, key);    if (I >= 0) {        mvalues[i] = value;    } else {        i = ~i;        if (i < msize && mvalues[i] = = DELETED) {            mkeys[i] = key;            Mvalues[i] = value;            return;        }        if (mgarbage && msize >= mkeys.length) {            gc ();            Search again because indices may have changed.            i = ~containerhelpers.binarysearch (Mkeys, msize, key);        }        Mkeys = Growingarrayutils.insert (Mkeys, msize, I, key);        Mvalues = Growingarrayutils.insert (mvalues, Msize, I, value);        msize++;    }
Thus, Sparsearray is a class written specifically for the hashmap of <Interger,Object> in Android, and its core is the binary lookup function (binarysearch), which can speed up the search efficiency, However, when data is inserted or deleted, the efficiency is not high. Memory efficiency should be similar to HashMap, can not be intuitively judged good or bad, need to discuss the situation.


Data structures for HashMap and Sparsearray in Java

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.