Created
February 22, 2016 22:24
-
-
Save Jire/433458f48d2bcf7ecf1d to your computer and use it in GitHub Desktop.
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.* | |
| class JireMap<K, V>(val capacity: Int = 16) : Iterable<JireMap.Entry<K, V>> { | |
| data class Entry<K, V>(val key: K, val value: V, var next: Entry<K, V>? = null) | |
| private var table = arrayOfNulls<Entry<K, V>>(capacity) | |
| fun K.hash() = Math.abs(hashCode()) % table.size | |
| @JvmName("put") | |
| operator fun set(key: K, value: V) { | |
| key!! | |
| val hash = key.hash() | |
| val entry = Entry(key, value) | |
| if (table[hash] != null) { | |
| var previous: Entry<K, V>? = null | |
| var current = table[hash] | |
| while (current != null) { | |
| if (key.equals(current.key)) { | |
| if (previous == null) { | |
| entry.next = current.next | |
| table[hash] = entry | |
| return | |
| } else { | |
| entry.next = current.next | |
| previous.next = entry | |
| return | |
| } | |
| } | |
| previous = current | |
| current = current.next | |
| } | |
| previous!!.next = entry | |
| } else table[hash] = entry | |
| } | |
| operator fun get(key: K): V? { | |
| key!! | |
| val hash = key.hash() | |
| if (table[hash] != null) { | |
| var temp = table[hash] | |
| while (temp != null) { | |
| if (key.equals(temp.key)) return temp.value | |
| temp = temp.next | |
| } | |
| } | |
| return null | |
| } | |
| private val iterator = object : Iterator<Entry<K, V>> { | |
| internal var next: Entry<K, V>? = null | |
| internal var current: Entry<K, V>? = null | |
| internal var index = 0 | |
| fun reset() { | |
| current = null | |
| next = null | |
| index = 0 | |
| while (index < table.size) { | |
| next = table[index++] | |
| if (next != null) break | |
| } | |
| } | |
| override fun next(): Entry<K, V> { | |
| var e = next ?: throw NoSuchElementException() | |
| current = e | |
| next = current!!.next | |
| if (next == null) while (index < table.size) { | |
| next = table[index++] | |
| if (next != null) break | |
| } | |
| return e | |
| } | |
| override fun hasNext(): Boolean { | |
| val hasNext = next != null | |
| if (!hasNext) iterating = false | |
| return hasNext | |
| } | |
| } | |
| private var iterating = false | |
| override fun iterator(): Iterator<Entry<K, V>> { | |
| if (iterating) throw IllegalStateException("You cannot iterate within an iteration!") | |
| iterating = true | |
| iterator.reset() | |
| return iterator | |
| } | |
| fun clear() { | |
| for (i in 0..table.size - 1) table[i] = null | |
| } | |
| fun putAll(map: JireMap<K, V>) { | |
| for ((k, v) in map) this[k] = v | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment