更改不可变 Map 的构建方式;改用静态工厂方法创建 ValueSet 对象。

This commit is contained in:
2023-04-30 11:14:28 +08:00
parent 404188abda
commit 1c5d5d4129
2 changed files with 19 additions and 13 deletions

View File

@@ -17,11 +17,13 @@
package xyz.zhouxy.plusone.commons.util;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import xyz.zhouxy.plusone.commons.annotation.StaticFactoryMethod;
/**
* 枚举类
*/
@@ -30,8 +32,9 @@ public abstract class Enumeration<T extends Enumeration<T>> implements Comparabl
protected final String name;
protected Enumeration(final int id, final String name) {
Assert.hasText(name, "Name of enumeration must has text.");
this.id = id;
this.name = Objects.requireNonNull(name);
this.name = name;
}
public final int getId() {
@@ -70,16 +73,20 @@ public abstract class Enumeration<T extends Enumeration<T>> implements Comparabl
}
protected static final class ValueSet<T extends Enumeration<T>> {
private final Map<Integer, T> valueMap;
private final ImmutableMap<Integer, T> valueMap;
private ValueSet(ImmutableMap<Integer, T> valueMap) {
this.valueMap = valueMap;
}
@SafeVarargs
public ValueSet(T... values) {
Map<Integer, T> temp = new HashMap<>(values.length);
@StaticFactoryMethod(ValueSet.class)
public static <T extends Enumeration<T>> ValueSet<T> of(T... values) {
Builder<Integer, T> builder = ImmutableMap.builder();
for (T value : values) {
Assert.notNull(value, "Value must not be null.");
temp.put(value.getId(), value);
builder.put(value.getId(), value);
}
this.valueMap = Collections.unmodifiableMap(temp);
return new ValueSet<>(builder.build());
}
public T get(int id) {