Data Structure of HashMap and SparseArray in Java

Source: Internet
Author: User

Data Structure of HashMap and SparseArray in Java

Recently, I heard from my colleagues that replacing HashMap with SparseArray can improve the performance, so we can perform a simple analysis on the data structures of these two classes.

Data Structure of Hashmap

Hashmap is a combination of arrays and linked lists (called "linked list hash" in the data structure), as shown in:

Image Source: Java HashMap and HashTable

SparseArray Data Structure

SparseArray refers to a Sparse array (Sparse array). To save memory space, it does not affect the original content values in the array. There are two key members, mKeys and mValues, both 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++;    }
It can be seen that SparseArray is The core of this Hashmap-specific class is the binarySearch function, which can accelerate the search efficiency. However, when data is inserted or deleted, the efficiency is not high. The memory efficiency should be similar to that of HashMap, so it cannot be intuitively determined whether the memory is good or bad. It should be discussed in different situations.

 

 

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.