Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
package com.example;
import android.util.SparseArray;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import static com.example.Size.ValidSize.SIZE_L;
import static com.example.Size.ValidSize.SIZE_M;
import static com.example.Size.ValidSize.SIZE_S;
public enum Size {
private volatile static SparseArray<Size> rawValueToEnum;
private final int rawValue;
Size(@ValidSize int rawValue) {
this.rawValue = rawValue;
public int getRawValue() {
return rawValue;
public @interface ValidSize {
int SIZE_L = 1;
int SIZE_M = 2;
int SIZE_S = 3;
public static Size fromRawValue(int rawValue) {
if (rawValueToEnum == null) {
final SparseArray<Size> sizeSparseArray = new SparseArray<>();
final Size[] values = values();
for (Size size : values) {
sizeSparseArray.append(size.getRawValue(), size);
// おまけ。値の重複チェックをしておく
if (sizeSparseArray.size() != values.length) {
throw new IllegalStateException("duplicate rawValues in Size enum");
rawValueToEnum = sizeSparseArray;
final Size size = rawValueToEnum.get(rawValue);
if (size == null) {
throw new IllegalArgumentException("invalid rawValue: " + rawValue);
return size;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.