【移动开发】SparseArray替代HashMap

SparseArray是android里为<Interger,Object>这样的Hashmap而专门写的class,目的是提高效率,其核心是折半查找函数(binarySearch)。

  1. private static int binarySearch(int[] a, int start, int len, int key) {  
  2.     int high = start + len, low = start - 1, guess;  
  3.     while (high - low > 1) {  
  4.         guess = (high + low) / 2;  
  5.         if (a[guess] < key)  
  6.             low = guess;  
  7.         else  
  8.             high = guess;  
  9.     }  
  10.     if (high == start + len)  
  11.         return ~(start + len);  
  12.     else if (a[high] == key)  
  13.         return high;  
  14.     else  
  15.         return ~high;  
  16. }  

所以,它存储的数值都是按键值从小到大的顺序排列好的。

添加数据:

  1. public void put(int key, E value) {}  
  2. public void append(int key, E value){}  

删除操作:

  1. public void delete(int key) {}  
  2. public void remove(int key) {}   
  3. public void removeAt(int index){}  
  4. public void clear(){}  

修改数据:

  1. public void put(int key, E value)  
  2. public void setValueAt(int index, E value)  

查找数据:

  1. public E get(int key)  
  2. public E get(int key, E valueIfKeyNotFound)  

相应的也有SparseBooleanArray,用来取代HashMap<Integer, Boolean>,SparseIntArray用来取代HashMap<Integer, Integer>。

SparseArray是android里为<Interger,Object>这样的Hashmap而专门写的类,目的是提高效率,其核心是折半查找函数(binarySearch)。当需要定义

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

时,可以使用如下的方式来取得更好的性能。

原文地址:https://www.cnblogs.com/xiaomaohai/p/6158026.html