Created
January 10, 2014 07:13
-
-
Save dvalfrid/8348090 to your computer and use it in GitHub Desktop.
Enum lookup Map
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
// Först behöver vi ett interface | |
package net.valfridsson; | |
public interface IdentityEnum<I, E extends Enum<E>> { | |
/** | |
* @return Hämtar ut {@link I} för {@link E} | |
*/ | |
I getId(); | |
} | |
// Sedan behövver vi mekanismen som hanterar uppslagen mellan enumarna | |
package net.valfridsson; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.Set; | |
public class EnumLookupMap<I, E extends Enum<E> & IdentityEnum<I, E>> { | |
private Map<I, E> map = new HashMap<I, E>(); | |
public EnumLookupMap(Class<E> clazz) { | |
for (E e : clazz.getEnumConstants()) { | |
map.put(e.getId(), e); | |
} | |
} | |
public E get(I key) { | |
return map.get(key); | |
} | |
public Set<Map.Entry<I, E>> getEntries() { | |
return map.entrySet(); | |
} | |
} | |
// Hur använder vi den: | |
private enum EnumB { | |
VALUE_1, VALUE_2; | |
} | |
private enum EnumA implements IdentityEnum<EnumB, EnumA> { | |
VALUE_1(EnumB.VALUE_1),VALUE_2(EnumB.VALUE_2); | |
private EnumB enumb; | |
public static EnumLookupMap<EnumB, EnumA> map = new EnumLookupMap<EnumB, EnumA>(EnumA.class); | |
private EnumA(EnumB enumb) { | |
this.enumb = enumb; | |
} | |
public static EnumA valueOf(EnumB enumB){ | |
return map.get(enumB); | |
} | |
public EnumB getId() { | |
return enumb; | |
} | |
} | |
// Man kan nu hämta ut EnumB från EnumA - getId() | |
// samt få ut EnumA utifrån EnumB - valueOf(EnumB enum) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment