gpt4 book ai didi

java - 使用类作为变量标识符?

转载 作者:行者123 更新时间:2023-12-02 06:34:27 24 4
gpt4 key购买 nike

我正在制作几个简单的类来计算垄断游戏中的一些内容。

我的第一个类(BoardSquare)有方法来获取和设置玩家ID广场名称和广场上的房屋数量,而我有另一种方法根据广场上的房屋数量使用if语句计算租金。

我的第二个类(House)有一个方法,可以在另一个 if 语句中获取新房子的特性成本,然后有一个 set 方法来设置房价。

我的目标是在 boardsquare 类中使用 House 类。我的意思是,而不是有一个实例变量

    int houses;

为了保存正方形上房屋的数量,我使用 House 类型的变量。换句话说,一个正方形上不是有很多房子,而是有 0 或 1 个房子。

我知道自己想做什么,只是不知道该怎么做。

所以我有一个实例变量 房屋房屋;我的 getHouses 方法读取

    public House getHouses(this is where i had int h(from the constructor) but I dont know what to put here now)
{
Whatever I need to put here to access the class House
}

希望您能理解我想要实现的目标。如果您能提供任何提示,我将不胜感激。

最佳答案

您想要 Collection<House> .

请勿使用LinkedList<House>除非您需要链表的特定行为。这也适用于 ArrayList 。您可能需要其中任何一个作为实现,但请尽可能使用最抽象的集合。

  • List房子的顺序很重要
  • Set如果您只想强制执行每种类型房屋的一个实例(可能不适用)

所以:

Collection<House> houses = new ArrayList<House>();

public Collection<House> getHouses() {
return houses;
}

public void addHouse(House newHouse) {
houses.add(newHouse);
}

我选择了 ArrayList实现,因为将新元素添加到列表末尾是有效的。 LinkedList 也是如此。 ,但是LinkedList增加了额外的开销,使得将条目插入 List 更加高效。请参阅文档以获取更多信息。

关于java - 使用类作为变量标识符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19798242/

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