gpt4 book ai didi

java - 设置: Prevent insertion of same type

转载 作者:行者123 更新时间:2023-12-02 02:20:44 25 4
gpt4 key购买 nike

如果已存在相同类型的对象,我想阻止在 Set 中插入对象。示例:

如果我有以下类(class):

public class Card{...}
public class Clubs extends Card{...}
public class Diamonds extends Card{...}
public class Hearts extends Card{...}
public class Spades extends Card{...}

行为应该是:

Set<Card> cards = new HashSet<>();
System.out.println(cards.add(new Diamonds()) //prints "true"
System.out.println(cards.add(new Spades()) //prints "true"
System.out.println(cards.add(new Spades()) //prints "false"

是否有一种简单的方法或一组实现可以给我这种行为?

我考虑过为扩展 Card 的每个类重写 hashcode/equals 来管理哈希集行为,但我认为这不是一个可靠的解决方案。

编辑:

我以一张基本的牌为例,但每张牌不仅仅是一种“颜色”,字段的数量、字段的类型和每个类(梅花、方 block 、黑桃、红心)的方法都不同。

编辑2

这是我的 Card 类的更具体定义:

public abstract class Card
{
/**Keyword of this card*/
private final String keyword;

public Card(String keyword)
{
this.keyword = keyword;
}

public abstract void cardDefinition();
...
}

这里是我的类扩展卡的定义:

public class Diamonds extends Card
{
/**KEYWORD of this card*/
public static final String KEYWORD = "cell";
/**Name of this cell*/
private final int id;
/**Universe of this cell*/
private final Universe universe;
/**Material name of this cell*/
private final String materialName;

public Diamonds(int id, Universe universe, String materialName)
{
super(KEYWORD);
this.id = id;
this.universe = universe;
this.materialName = materialName;
...
}
@Override
public void cardDefinition(){...}
public void someMethod(OrientedSurface orientedSurface) {...}
...
}


public class Spades extends Card
{
/**keyword of this card*/
public static final String KEYWORD = "mat";
/**Name of this material card*/
private final String name;
/**Density of this material card*/
private final double density;'

public Spades(String name, double density)
{
super(KEYWORD);
this.name = name;
this.density = density;
...
}
@Override
public void cardDefinition(){...}
public void someMethodBis(Material material) {...}
...
}
...

最佳答案

根据您更新的答案,也许使用关键字到卡片的映射可能适合您:

Map<String, Card> cards = new HashMap<>();

这是假设关键字是唯一的,并且每个关键字只能在 map 中出现一张卡片。在 map 中存储数据可能如下所示:

Card mySpade = new Spade(...);

if (!cards.contains(Spades.KEYWORD)) {
cards.put(Spades.KEYWORD, mySpade);
}...

关于java - 设置: Prevent insertion of same type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48539398/

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