gpt4 book ai didi

Java - 转换 Set 的缺点?

转载 作者:行者123 更新时间:2023-11-30 01:46:27 25 4
gpt4 key购买 nike

为了好玩,我正在用 Java 开发一个基于实体组件系统的基本游戏引擎。

我需要一种快速的方法来获取所有Component某种类型的s。示例:

public class MovementSystem extends System {
@Override
public void update() {
Set<Location> locations = ComponentManager.getActiveComponents(Location.class);
for (Location locationComponents : locations) {
// do stuff
}
}
}

所以我有一个 ComponentManager应该可以处理这个问题:

public class ComponentManager {
private static final Map<Class<? extends Component>, Set<Component>> active = new HashMap<>();

public static void activate(Component component) {
// if component.class does not have an entry in
// active yet, initialize with new HashSet
active.computeIfAbsent(component.getClass(), compClass -> new HashSet<>());
active.get(component.getClass()).add(component);
}
public static void deactivate(Component component) {
Set<Component> comps = active.get(component.getClass());
if (comps != null)
comps.remove(component);
}
public static <T extends Component> Set<T> getActiveComponents(Class<T> compClass) {
return (Set<T>) active.get(compClass);
}
}

我的 IDE 不喜欢 (Set<T>) active.get(compClass); (以黄色突出显示)。然而,这基于非常基本的测试,并且比单独类型转换 Set 中的每个项目更快。并将它们添加到新的 Set 中,但是这样做有哪些潜在的缺点呢?

最佳答案

您看到的 IDE 警告是未经检查的转换。

在这里您指定返回 getActiveComponents()Set<Location> :

Set<Location> locations = ComponentManager.getActiveComponents(Location.class);

但根据对象的来源,它可能是 Component 的任意类型s (您从 Set<Component> 获取它),不一定是 Location s:

private static final Map<Class<? extends Component>, Set<Component>> active = new HashMap<>();

当你使用它时:

 return (Set<T>) active.get(compClass);

but what are the potential downsides to doing this?

今天您的代码是正确的,因为它添加了 Map其值的条目,其中 Set 的对象将类的运行时类型用作键。
但是,如果稍后代码在映射中添加不遵循此规则的内容,则编译器将无法检测到键入错误。
所以你只会在运行时发现它:这是缺点。

你的情况很糟糕吗?这取决于。
当您开发某种按类型/类别操作/分组对象的库时,可能会发生此类问题。您通常必须研究类型安全性和代码灵 active /可维护性之间的平衡。
在这里,您“失去”类型安全性,以减少需要维护的结构数量。
如果您的Component数量有限子类并且它不会移动,您可以将 map 分解为几组:每个子类一组。这样,您就不会再进行未经检查的转换。
但如果Component的数量子类很重要并且它会移动(您可以及时添加或删除它),未经检查的转换警告可能是可以接受的。在这种情况下,编写一个单元测试来确保您仅检索预期类型的​​实例是非常受欢迎的,因为这可以保证当您执行未经检查的转换时编译器无法为您执行此操作。

关于Java - 转换 Set 的缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57751131/

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