Created
March 9, 2013 15:26
-
-
Save anonymous/5124500 to your computer and use it in GitHub Desktop.
This file contains 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
class EnumMap[K <: Enum[_], +T] private (values: Array[T]) | |
(implicit m: Manifest[K]) | |
extends Map[K, T] { | |
def this()(implicit k: Manifest[K], t: Manifest[T]) = | |
this(t.newArray(k.erasure.getEnumConstants.length))(k) | |
val notNulls = values.count(_ != null) | |
def get(key: K) = { | |
val value = values(key.ordinal()) | |
if (value != null) Some(value) else None | |
} | |
def iterator = new Iterator[(K, T)] { | |
var index: Int = -1; | |
def hasNext = index < notNulls - 1 | |
@tailrec | |
private def nextNonNullIndex(index:Int):Int= | |
if (values(index)!=null) index | |
else nextNonNullIndex(index+1) | |
def next() = { | |
val value = values(nextNonNullIndex(index+1)); | |
val key = m.erasure.getEnumConstants()(index).asInstanceOf[K] | |
(key, value) | |
} | |
} | |
def -(key: K) = get(key) match { | |
case None => this | |
case Some(_) => { | |
this.+((key, null)) | |
} | |
} | |
def +[B1 >: T](kv: (K, B1)) = { | |
val newArray = values.clone() | |
newArray(kv._1.ordinal()) = kv._2.asInstanceOf[T] | |
new EnumMap(newArray) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment