Created
August 13, 2014 07:00
-
-
Save pingany/269dda8502884711ed3b to your computer and use it in GitHub Desktop.
make SparseArray can be used in enhanced-for
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.Iterator; | |
| import android.util.SparseArray; | |
| public class SparseArrayUtils { | |
| private static abstract class IndexIterator<IterType, Type> implements Iterator<IterType> { | |
| protected int mIndex = 0; | |
| protected SparseArray<Type> mArray; | |
| public IndexIterator(SparseArray<Type> array) { | |
| mArray = array; | |
| } | |
| @Override | |
| public boolean hasNext() { | |
| return mIndex < mArray.size(); | |
| } | |
| @Override | |
| public void remove() { | |
| mArray.removeAt(mIndex); | |
| } | |
| } | |
| public static class Entry<Type> { | |
| final int key; | |
| final Type value; | |
| Entry(int key, Type value) { | |
| this.key = key; | |
| this.value = value; | |
| } | |
| } | |
| private static <IterType> Iterable<IterType> createIterable(final Iterator<IterType> iter) { | |
| return new Iterable<IterType>() { | |
| @Override | |
| public Iterator<IterType> iterator() { | |
| return iter; | |
| } | |
| }; | |
| } | |
| public static <Type> Iterable<Type> values(SparseArray<Type> array) { | |
| return createIterable(new IndexIterator<Type, Type>(array) { | |
| @Override | |
| public Type next() { | |
| return mArray.valueAt(mIndex++); | |
| } | |
| }); | |
| } | |
| public static <Type> Iterable<Integer> keys(SparseArray<Type> array) { | |
| return createIterable(new IndexIterator<Integer, Type>(array) { | |
| @Override | |
| public Integer next() { | |
| return mArray.keyAt(mIndex++); | |
| } | |
| }); | |
| } | |
| public static <Type> Iterable<Entry<Type>> entries(SparseArray<Type> array) { | |
| return createIterable(new IndexIterator<Entry<Type>, Type>(array) { | |
| @Override | |
| public Entry<Type> next() { | |
| Entry<Type> e = new Entry<Type>(mArray.keyAt(mIndex), mArray.valueAt(mIndex)); | |
| mIndex++; | |
| return e; | |
| } | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment