重构 Enumeration 类。

feature/net-util
ZhouXY108 2023-04-15 02:47:11 +08:00
parent 3218a2289a
commit 0fa1fc3964
1 changed files with 40 additions and 23 deletions

View File

@ -16,37 +16,47 @@
package xyz.zhouxy.plusone.commons.util; package xyz.zhouxy.plusone.commons.util;
import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nonnull;
/** /**
* *
*/ */
public abstract class Enumeration<T extends Enumeration<T>> { public abstract class Enumeration<T extends Enumeration<T>> implements Comparable<T> {
protected final int value; protected final int id;
@Nonnull
protected final String name; protected final String name;
protected Enumeration(int value, String name) { protected Enumeration(int id, @Nonnull String name) {
this.value = value; this.id = id;
this.name = name; this.name = name;
} }
public int getValue() { public final int getId() {
return value; return id;
} }
public String getName() { @Nonnull
public final String getName() {
return name; return name;
} }
@Override @Override
public int hashCode() { public final int compareTo(T o) {
return Objects.hash(value); return Integer.compare(this.id, o.id);
} }
@Override @Override
public boolean equals(Object obj) { public final int hashCode() {
return Objects.hash(id);
}
@Override
public final boolean equals(Object obj) {
if (this == obj) if (this == obj)
return true; return true;
if (obj == null) if (obj == null)
@ -54,30 +64,37 @@ public abstract class Enumeration<T extends Enumeration<T>> {
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
Enumeration<?> other = (Enumeration<?>) obj; Enumeration<?> other = (Enumeration<?>) obj;
return value == other.value; return id == other.id;
} }
@Override @Override
public String toString() { @Nonnull
return "[" + value + ": " + name + "]"; public final String toString() {
return getClass().getSimpleName() + "[" + id + ": " + name + "]";
} }
protected static final class EnumerationValuesHolder<T extends Enumeration<T>> { protected static final class ValueSet<T extends Enumeration<T>> {
private final Map<Integer, T> constants = new ConcurrentHashMap<>(); private final Map<Integer, T> values = new ConcurrentHashMap<>();
@SafeVarargs @SafeVarargs
public EnumerationValuesHolder(T... values) { public ValueSet(T... values) {
for (T value : values) { for (T value : values) {
put(value); put(Objects.requireNonNull(value));
} }
} }
private void put(T constant) { private void put(@Nonnull T value) {
this.constants.put(constant.getValue(), constant); this.values.put(value.getId(), value);
} }
public T get(int value) { @Nonnull
return this.constants.get(value); public T get(int id) {
return Objects.requireNonNull(this.values.get(id));
}
@Nonnull
public Collection<T> getValues() {
return this.values.values();
} }
} }
} }