警告显示当我在android中使用哈希映射时(使用新的SparseArray <String>)

Nav*_*mar 65 android hashmap

我是Android的新手.在我正在使用的Android应用程序中HashMap,但我收到警告:

**"Use new SparseArray<String>(...) instead for better performance"**
Run Code Online (Sandbox Code Playgroud)

这意味着什么,我该如何使用SparseArray<String>呢?

Bha*_*iya 116

使用new SparseArray<String>(...)代替更好的性能

由于此处描述的原因,您收到此警告.

SparseArrays将整数映射到对象.与普通的对象数组不同,索引中可能存在间隙.它旨在比使用HashMap将整数映射到对象更有效.

现在

我如何使用SparseArray?

您可以通过以下方式实现:

  1. HashMap 办法:

    Map<Integer, Bitmap> _bitmapCache = new HashMap<Integer, Bitmap>();
    private void fillBitmapCache() {
         _bitmapCache.put(R.drawable.icon, BitmapFactory.decodeResource(getResources(), R.drawable.icon));
         _bitmapCache.put(R.drawable.abstrakt, BitmapFactory.decodeResource(getResources(), R.drawable.abstrakt));
         _bitmapCache.put(R.drawable.wallpaper, BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper));
         _bitmapCache.put(R.drawable.scissors, BitmapFactory.decodeResource(getResources(), 
     }
    
    Bitmap bm = _bitmapCache.get(R.drawable.icon);
    
    Run Code Online (Sandbox Code Playgroud)
  2. SparseArray 办法:

    SparseArray<Bitmap> _bitmapCache = new SparseArray<Bitmap>();
    private void fillBitmapCache() {
         _bitmapCache.put(R.drawable.icon, BitmapFactory.decodeResource(getResources(), R.drawable.icon));
         _bitmapCache.put(R.drawable.abstrakt, BitmapFactory.decodeResource(getResources(), R.drawable.abstrakt));
         _bitmapCache.put(R.drawable.wallpaper, BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper));
         _bitmapCache.put(R.drawable.scissors, BitmapFactory.decodeResource(getResources(), 
     }
    
    Bitmap bm = _bitmapCache.get(R.drawable.icon);
    
    Run Code Online (Sandbox Code Playgroud)

希望它会有所帮助.


Nic*_*son 42

SparseArray当您使用Integer键作为键时使用.

当使用时SparseArray,将始终作为基本变量保留,这与使用HashMap需要具有Object作为键的位置不同,这将导致int在Integer短时间内成为对象,同时获取对象地图.

通过使用SparseArray您将保存垃圾收集器一些工作.

所以就像使用一样Map<Integer,String>.

  • +1,避免HashMap发生的自动装箱(和关联的对象+ GC).@ cyril-mottier在这里写到:https://speakerdeck.com/cyrilmottier/optimizing-android-ui-pro-tips-for-creating-smooth-and-responsive-apps (5认同)

Chr*_*bin 5

这暗示您的代码有更好的数据结构.

这个提示来自Lint.当你有一个HashMap整数到其他东西时,你通常会得到它.

它的最大优点是将整数键视为基元.换句话说,它不会转换为Integer(Java对象)将其用作键.

使用大型地图时,这是一个大问题.在这种情况下HashMap,将导致创建许多很多Integer对象.

在这里查看更多信息.