gpt4 book ai didi

java - 我可以在 HashMap 中通过 Key 实现类型安全吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:11:17 25 4
gpt4 key购买 nike

要解决以下场景:我需要创建一个类,它会根据给定的 id+classtype 返回或存储水果列表。所以我在质疑自己,哪个Collection使用,如果我能够将所有水果列表存储在同一个 Collection 中对于简单的城市。我决定给一个 HashMap尝试存储所有列表,因为键值原则听起来对我的用例很熟悉,只是它可能需要一些更复杂的键,因为我需要两个方面(在我的例子中是 id 和 fruits 类)来识别值(value)。

所以我创建了一个自己的关键对象:

class FruitKey
{
int id;
Class<? extends Fruits> type;

public FruitKey( int id, Class<? extends Fruits> type )
{
this.id = id;
this.type = type;
}

//equals, hashcode, etc.
}

创建 Map<FruitKey, List<? extends Fruits>> 之后,放置效果非常好,但是当然,当我尝试从 map 中取出我的 FruitLists 时,我不能保证特定的水果类型并且必须转换结果:

public static void main( String[] args )
{
Map<FruitKey, List<? extends Fruits>> fruitMap = new HashMap<>();

Apple oneApple = new Apple();
List<Apple> manyApples = new ArrayList<>();
manyApples.add( oneApple );

fruitMap.put( new FruitKey( 1, Apple.class ), manyApples);

//Any way to avoid typesafty and cast?
List<Apple> myApples = (List<Apple>) fruitMap.get( new FruitKey( 1, Apple.class ) );
}

由于类类型已经包含在键中,我不知何故认为我可以将它们与 map 值联系起来,但不幸的是我没有成功,没有将 map 专门用于一种特殊的水果。您是否有机会避免我的类型安全/类转换问题,或者可以推荐另一种集合类型来实现我的目标?当然,我可以为每种水果创建一个 map ,但由于那里有很多 yummi 水果,我尽量避免使用它,因为我总是不得不区分它们。

简而言之,这就是我想要的:

List<Apple> apples = SomeCollection.get( Key(id, Apple.class) );

还有一个 Id 的原因是,在同一个 map 中可以有多个苹果列表,以及多个其他水果列表。

最佳答案

您可以使用异构容器。您仍然需要在容器内进行转换,但是由于通用方法和 final类(class)的 Actor 是安全的,您可以取消警告。

这是安全的,因为通用 put确保您永远不会放入任何会导致 Actor 失败的东西。

public final class SomeCollection {

private Map<FruitKey<? extends Fruits>, List<? extends Fruits>> fruitMap = new HashMap<>();

//safe cast
@SuppressWarnings("unchecked")
public <T extends Fruits> List<T> get(FruitKey<T> key)
{
return (List<T>) fruitMap.get(key);
}

public <T extends Fruits> void put(FruitKey<T> key, List<T> fruits)
{
fruitMap.put(key, fruits);
}
}

输入 FruitKey

class FruitKey<T extends Fruits>
{
int id;
Class<T> type;

public FruitKey( int id, Class<T> type )
{
this.id = id;
this.type = type;
}
}

编辑

您还可以创建一个内部类 Key<T>里面SomeCollection , 它封装了一个 FruitKey篮子和适当的hashCodeequals .

private Map<Key<? extends Fruits>, List<? extends Fruits>> fruitMap = new HashMap<>();

//safe cast
@SuppressWarnings("unchecked")
public <T extends Fruits> List<T> getBasket(T fruit)
{
Key<T extends Fruit> = new Key<T>(fruit.getBasketId());
return (List<T>) fruitMap.get(key);
}
//or
//safe cast
@SuppressWarnings("unchecked")
public <T extends Fruits> List<T> getBasket(Class<T> klass, FruitKey key)
{
Key<T extends Fruit> = new Key<T>(key);
return (List<T>) fruitMap.get(key);
}

public <T extends Fruits> void addToBasket(T fruit, List<T> fruits)
{
Key<T extends Fruit> = new Key<T>(fruit.getBasketId());
fruitMap.put(key, fruits);
}

关于java - 我可以在 HashMap 中通过 Key 实现类型安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13307686/

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