How to initialize a static SparseArray

How can I initialize a static , non-modifiable instance of android.util.SparseArray ?

+7
source share
3 answers

You cannot do what you are trying to do. At least not how you are trying to do this. There is no SparseArray implementation that is not SparseArray .

However, you can create it. Here's how:

  • Create a class, say CustomSparseArray<E> , and extend it with a SparseArray .
  • Override all methods that modify elements in an array and replace them in approximately the following way:

     @Override public void append(int key, E value) { if (mLocked) return; // Maybe throw an exception super.append(key, value); } 
  • Then add the member variable to the class, boolean mLocked = false; .
  • Then you need the following method:

     public void lock() { mLocked = true; } 
  • Finally, use a static variable using a method similar to another post :

     public class Test { private static final CustomSparseArray<Integer> myArray; static { myArray = new CustomSparseArray<Integer>(); myArray.append(1, 1); myArray.append(2, 5); myArray.lock(); } } 

Then you have an unmodifiable SparseArray in your static myArray variable.

+6
source

Here is the best way to use an anonymous class:

 static final SparseIntArray myArray = new SparseIntArray() { { append(1, 2); append(10, 20); } }; 
+15
source

This works for me:

 static final SparseIntArray CMyArray = new SparseIntArray(); static { CMyArray.append(2, 4); CMyArray.append(8, 3); CMyArray.append(255, 1); } 

according to: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

0
source

All Articles