gpt4 book ai didi

Java Hashmap 仅在键中存储特定类型的值

转载 作者:行者123 更新时间:2023-11-30 05:51:22 25 4
gpt4 key购买 nike

我正在考虑创建一个 Hashmap 类,它允许我存储键和值。但是,只有当该值与特定类型匹配时才能存储该值,并且该类型取决于键的运行时值。例如,如果键为 EMAIL(String.class),则存储的值应为 String 类型。

我有以下自定义枚举:

public enum TestEnum {
TDD,
BDD,
SHIFT_RIGHT,
SHIFT_LEFT;
}

我创建了以下类(class):

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class test {

private static final Map<ValidKeys, Object> sessionData = new HashMap<>();

public enum ValidKeys {
EMAIL(String.class),
PASSWORD(String.class),
FIRST_NAME(String.class),
LAST_NAME(String.class),
CONDITION(TestEnum.class);

private Class type;
private boolean isList;
private Pattern pattern;

ValidKeys(Class<?> type, boolean isList) {
this.type = type;
this.isList = isList;
}

ValidKeys(Class<?> type) {
this.type = type;
}
}

public <T> void setData(ValidKeys key, T value) {
sessionData.put(key,value);
}


public Object getData(ValidKeys key) {
return key.type.cast(sessionData.get(key));
}


public static void main(String[] args) {
test t = new test();
t.setData(ValidKeys.CONDITION,TestEnum.TDD);
System.out.println(t.getData(ValidKeys.CONDITION));
}
}

我想使用 setDatagetData 等方法并将值存储到 sessionData 中。另外,我想确保该值是否是对象列表,然后也可以正确存储。

我也在努力避免 toString 基本上我需要一个通用的 getData ,它可以在没有类型转换的情况下工作。

最佳答案

我见过一种用于此类事情的特殊模式,它是 Bloch 的类型安全异构容器模式的变体。我不知道它是否有自己的名称,但由于缺乏更好的名称,我将其称为 Typesafe Enumerated Lookup Keys。

基本上,我在各种上下文中看到的一个问题是您需要一组动态的键/值对,其中键的特定子集是具有预定义语义的“众所周知”。此外,每个键都与特定类型相关联。

“显而易见”的解决方案是使用枚举。例如,您可以这样做:

public enum LookupKey { FOO, BAR }

public final class Repository {
private final Map<LookupKey, Object> data = new HashMap<>();

public void put(LookupKey key, Object value) {
data.put(key, value);
}

public Object get(LookupKey key) {
return data.get(key);
}
}

这工作得很好,但明显的缺点是现在你需要到处转换。例如,假设您知道 LookupKey.FOO总是有一个String值,和LookupKey.BAR总是有一个Integer值(value)。你如何执行这一点?通过此实现,您不能。

此外:通过此实现,键集由枚举固定。您无法在运行时添加新的。对于某些应用程序来说这是一个优势,但在其他情况下,您确实希望在某些情况下允许使用新 key 。

这两个问题的解决方案基本上是相同的:make LookupKey一个一流的实体,而不仅仅是一个枚举。例如:

/**
* A key that knows its own name and type.
*/
public final class LookupKey<T> {
// These are the "enumerated" keys:
public static final LookupKey<String> FOO = new LookupKey<>("FOO", String.class);
public static final LookupKey<Integer> BAR = new LookupKey<>("BAR", Integer.class);

private final String name;
private final Class<T> type;

public LookupKey(String name, Class<T> type) {
this.name = name;
this.type = type;
}

/**
* Returns the name of this key.
*/
public String name() {
return name;
}

@Override
public String toString() {
return name;
}

/**
* Cast an arbitrary object to the type of this key.
*
* @param object an arbitrary object, retrieved from a Map for example.
* @throws ClassCastException if the argument is the wrong type.
*/
public T cast(Object object) {
return type.cast(object);
}

// not shown: equals() and hashCode() implementations
}

这已经让我们完成了大部分工作。您可以引用LookupKey.FOOLookupKey.BAR它们的行为就像您所期望的那样,但它们也知道相应的查找类型。您还可以通过创建 LookupKey 的新实例来定义自己的 key 。 .

如果我们想实现一些不错的类似枚举的功能,例如 static values()方法,我们只需要添加一个注册表即可。作为奖励,我们甚至不需要 equals()hashCode()如果我们添加一个注册表,因为我们现在可以通过身份比较查找键。

以下是该类最终的样子:

/**
* A key that knows its own name and type.
*/
public final class LookupKey<T> {
// This is the registry of all known keys.
// (It needs to be declared first because the create() function needs it.)
private static final Map<String, LookupKey<?>> knownKeys = new HashMap<>();

// These are the "enumerated" keys:
public static final LookupKey<String> FOO = create("FOO", String.class);
public static final LookupKey<Integer> BAR = create("BAR", Integer.class);


/**
* Create and register a new key. If a key with the same name and type
* already exists, it is returned instead (Flywheel Pattern).
*
* @param name A name to uniquely identify this key.
* @param type The type of data associated with this key.
* @throws IllegalStateException if a key with the same name but a different
* type was already registered.
*/
public static <T> LookupKey<T> create(String name, Class<T> type) {
synchronized (knownKeys) {
LookupKey<?> existing = knownKeys.get(name);
if (existing != null) {
if (existing.type != type) {
throw new IllegalStateException(
"Incompatible definition of " + name);
}
@SuppressWarnings("unchecked") // our invariant ensures this is safe
LookupKey<T> uncheckedCast = (LookupKey<T>) existing;
return uncheckedCast;
}
LookupKey<T> key = new LookupKey<>(name, type);
knownKeys.put(name, key);
return key;
}
}

/**
* Returns a list of all the currently known lookup keys.
*/
public static List<LookupKey<?>> values() {
synchronized (knownKeys) {
return Collections.unmodifiableList(
new ArrayList<>(knownKeys.values()));
}
}

private final String name;
private final Class<T> type;

// Private constructor. Only the create method should call this.
private LookupKey(String name, Class<T> type) {
this.name = name;
this.type = type;
}

/**
* Returns the name of this key.
*/
public String name() {
return name;
}

@Override
public String toString() {
return name;
}

/**
* Cast an arbitrary object to the type of this key.
*
* @param object an arbitrary object, retrieved from a Map for example.
* @throws ClassCastException if the argument is the wrong type.
*/
public T cast(Object object) {
return type.cast(object);
}
}

现在LookupKey.values()或多或少像枚举一样工作。您还可以添加自己的 key ,以及 values()之后将返回它们:

LookupKey<Double> myKey = LookupKey.create("CUSTOM_DATA", Double.class);

一旦你有了这个LookupKey类,您现在可以实现一个使用这些键进行查找的类型安全存储库:

/**
* A repository of data that can be looked up using a {@link LookupKey}.
*/
public final class Repository {
private final Map<LookupKey<?>, Object> data = new HashMap<>();

/**
* Set a value in the repository.
*
* @param <T> The type of data that is being stored.
* @param key The key that identifies the value.
* @param value The corresponding value.
*/
public <T> void put(LookupKey<T> key, T value) {
data.put(key, value);
}

/**
* Gets a value from this repository.
*
* @param <T> The type of the value identified by the key.
* @param key The key that identifies the desired value.
*/
public <T> T get(LookupKey<T> key) {
return key.cast(data.get(key));
}
}

关于Java Hashmap 仅在键中存储特定类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53860603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com