Skip to content

Instantly share code, notes, and snippets.

@zaki50
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaki50/d09070c76f7532a7df1f to your computer and use it in GitHub Desktop.
Save zaki50/d09070c76f7532a7df1f to your computer and use it in GitHub Desktop.
package com.example;
import android.support.annotation.IntDef;
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 {
L(SIZE_L), M(SIZE_M), S(SIZE_S);
private volatile static SparseArray<Size> rawValueToEnum;
@ValidSize
private final int rawValue;
Size(@ValidSize int rawValue) {
this.rawValue = rawValue;
}
@ValidSize
public int getRawValue() {
return rawValue;
}
@Retention(RetentionPolicy.SOURCE)
@IntDef({SIZE_L, SIZE_M, SIZE_S})
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