diff options
author | Kazuki Yamaguchi <k@rhe.jp> | 2017-10-25 00:33:45 +0900 |
---|---|---|
committer | Kazuki Yamaguchi <k@rhe.jp> | 2017-10-25 00:33:45 +0900 |
commit | 065e7a135b9817b94e397f7c21259699eb3b09be (patch) | |
tree | 36333ed9162bf360ab1dc8720c8b883f418903d9 /app/src/main/java/net/lacolaco/smileessence/util | |
parent | f294462478a82c9c0d18ccea28dda4f4b593f31d (diff) | |
download | SmileEssence-065e7a135b9817b94e397f7c21259699eb3b09be.tar.gz |
pieee
Diffstat (limited to 'app/src/main/java/net/lacolaco/smileessence/util')
-rw-r--r-- | app/src/main/java/net/lacolaco/smileessence/util/SortedList.kt | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/app/src/main/java/net/lacolaco/smileessence/util/SortedList.kt b/app/src/main/java/net/lacolaco/smileessence/util/SortedList.kt new file mode 100644 index 00000000..b0c0e205 --- /dev/null +++ b/app/src/main/java/net/lacolaco/smileessence/util/SortedList.kt @@ -0,0 +1,41 @@ +package net.lacolaco.smileessence.util + +import net.lacolaco.smileessence.entity.IdObject +import java.util.* + +class SortedList<T : IdObject> constructor( + private val onInserted: (Int) -> Unit, + private val onRemoved: (Int, Int) -> Unit, + initialCapacity: Int = 32 +) { + private var arrayList = ArrayList<T>(initialCapacity) + + fun add(item: T): Int { + val pos = arrayList.binarySearchBy(item.id, selector = { it.id }) + if (pos >= 0) + return applyReversedOrder(pos) + arrayList.add(-pos - 1, item) + onInserted(applyReversedOrder(-pos - 1)) + return applyReversedOrder(-pos - 1) + } + + fun addAll(items: Collection<T>) { + items.forEach { add(it) } + } + + operator fun get(index: Int): T { + return arrayList[applyReversedOrder(index)] + } + + fun clear() { + val size = arrayList.size + arrayList.clear() + onRemoved(0, size) + } + + val size + get() = arrayList.size + + private fun applyReversedOrder(pos: Int): Int + = arrayList.size - pos - 1 +} |