将 ValueSet 中的 Map 改为不可变集合。

feature/net-util
ZhouXY108 2023-04-29 15:08:26 +08:00
parent a771b207f8
commit c6ddb8ab1e
2 changed files with 14 additions and 16 deletions

View File

@ -17,11 +17,10 @@
package xyz.zhouxy.plusone.commons.util; package xyz.zhouxy.plusone.commons.util;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nonnull;
/** /**
* *
@ -71,26 +70,25 @@ public abstract class Enumeration<T extends Enumeration<T>> implements Comparabl
} }
protected static final class ValueSet<T extends Enumeration<T>> { protected static final class ValueSet<T extends Enumeration<T>> {
private final Map<Integer, @Nonnull T> values = new ConcurrentHashMap<>(); private final Map<Integer, T> valueMap;
@SafeVarargs @SafeVarargs
public ValueSet(T... values) { public ValueSet(T... values) {
Map<Integer, T> valueMap = new HashMap<>(values.length);
for (T value : values) { for (T value : values) {
put(value); Assert.notNull(value, "Value must not be null.");
valueMap.put(value.getId(), value);
} }
} this.valueMap = Collections.unmodifiableMap(valueMap);
private void put(final T value) {
this.values.put(value.getId(), Objects.requireNonNull(value, "Value must not be null."));
} }
public T get(int id) { public T get(int id) {
Assert.isTrue(this.values.containsKey(id), "%s 对应的值不存在", id); Assert.isTrue(this.valueMap.containsKey(id), "%s 对应的值不存在", id);
return this.values.get(id); return this.valueMap.get(id);
} }
public Collection<@Nonnull T> getValues() { public Collection<T> getValues() {
return this.values.values(); return this.valueMap.values();
} }
} }
} }

View File

@ -1,6 +1,6 @@
package xyz.zhouxy.plusone.commons; package xyz.zhouxy.plusone.commons;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertSame;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -17,8 +17,8 @@ class EnumerationTests {
@Test @Test
void testEnumeration() { void testEnumeration() {
assertTrue(EntityStatus.AVAILABLE == EntityStatus.of(0)); assertSame(EntityStatus.AVAILABLE, EntityStatus.of(0));
assertTrue(Result.SUCCESSFUL == Result.of(1)); assertSame(Result.SUCCESSFUL, Result.of(1));
Collection<Comparable<? extends Enumeration<?>>> enums = Lists.newArrayList(); Collection<Comparable<? extends Enumeration<?>>> enums = Lists.newArrayList();
enums.addAll(EntityStatus.constants()); enums.addAll(EntityStatus.constants());
enums.addAll(Result.constants()); enums.addAll(Result.constants());