gpt4 book ai didi

java - 无需强制转换即可将值添加到 HashMap

转载 作者:搜寻专家 更新时间:2023-11-01 02:57:55 25 4
gpt4 key购买 nike

我有一个名为 InterA 的接口(interface),它有一个方法调用 operate(),其返回值为 Result。

 public interface InterA<T>
{
Result operate(T source);
}

假设 MachineOperator 类和 CarOperator 类是上述具有两种 T 对象类型的实现。

 public class MachineOperator implements InterA<Machine>
{
Result operate(Machine source)
{
//Do some operation here and return result.
}
}

public class CarOperator implements InterA<Car>
{
Result operate(Car source)
{
//Do some operation here and return result.
}
}

我想将这些实现保存在一个映射中,这样当我给类时我就可以得到实现。所以我的 map 会是这样的。

Map<Class<?>, InterA<T>> map = new HashMap<>();

当我去填充 map 时,我必须执行以下操作,

map.put(Machine.class, (InterA<T>) new MachineOperator());
map.put(Car.class, (InterA<T>) new CarOperator());

有没有什么方法可以定义 map ,这样在添加时就不再需要转换了?

============================================= ==============

我也尝试了以下方法,可以在添加到 map 时避免强制转换。

public interface InterA
{
Result <T> operate(T source);
}

然后在每个实现中,我必须为每个 T 进行额外的转换。

public class MachineOperator implements InterA
{
< Machine> Result operate(Machine source)
{
(Machine) source; //Need to cast for Machine In-order to read attributes.
//Do some operation here and return result.
}
}

其中什么是正确的方法?有什么不同的解决方案吗?

最佳答案

您可以为您的 Map 编写一个包装器,以允许仅添加相应的 InterA 对象:

class ClassMap {
private Map<Class<?>, InterA<?>> map = new HashMap<>();
public <T> void put(Class<T> key, InterA<T> value) {
map.put(key, value);
}
//we suppress unchecked cast warning because for Class<T> key we can put only InterA<T> value
@SuppressWarnings("unchecked")
public <T> InterA<T> get(Class<T> key) {
return (InterA<T>) map.get(key);
}
}

然后你就可以这样使用了

ClassMap map = new ClassMap();
map.put(Machine.class, new MachineOperator());
InterA<Machine> operator = map.get(Machine.class);

关于java - 无需强制转换即可将值添加到 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47724111/

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