java - Android Studio : List with items (objects)

标签 java android arrays oop

我正在开发一款游戏,玩家可以获取/制作某种具有特定值(value)的元素。例如,我们有一个名为“Tool”的类,我想创建某种数组/列表,我可以在其中添加新项目并为每个项目分配特定值。

除此之外,我想以某种方式从列表中获取具有特定值的所有对象(例如,获取所有具有 booleanowned = true 的对象并对它们的所有值/统计数据求和)

这是我到目前为止所得到的:

工具类

class Tool extends Item{
private int fight, resource, building, crafting, clothing;


public Tool(int ID, String name, boolean owned, int fight, int resource, int building, int crafting, int clothing){
    this.setID(ID);
    this.setName(name);
    this.setOwned(owned);
    this.setFight(fight);
    this.setResource(resource);
    this.setBuilding(building);
    this.setCrafting(crafting);
    this.setClothing(clothing);
}

之后是一堆 getter 和 setter...

Game Start()(创建所有项目并将它们设置为owned=false)

public void StartGame() {

    // TOOLS

    ArrayList<Tool> tools = new ArrayList<>(); //ID, Name, Owned, Fight, Resource, Building, Crafting, Clothing
    tools.add(new Tool(1,"Hatchet",false,0,0,0,0,0));

更具体地说,我想创建一个函数,从列表中获取所有owned=true对象并总结它们的值(例如,总结所有值:战斗、资源、建筑等)

P.S.这是我第一次尝试使用对象和类进行编码,而且我对 Java 还比较陌生。尝试寻找解决方案,但不完全知道如何搜索,几天后我放弃并决定询问 StackOverflow。

最佳答案

您可能想要循环遍历 ArrayList 中的 Tool 对象,如下所示:

// A counter to keep count
int ownedSum = 0;

// For every Tool (t) in the list of Tools (tools)
for(Tool t : tools){

    // Check your condition e.g: if owned is true
    if(t.getOwned()){
        ownedSum += // put getters here for the values to sum up
    }
}

关于java - Android Studio : List with items (objects),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42490372/

相关文章:

java - 使用 Java 使用数据库每天重置自动编号

androidTestCompile mockito 给出错误

ios - 将结果从 Swift 数组传递到 Segue 到描述

PHP 与 array_filter 相反?

java - 从 Java 调用 GnuWin 命令还是有更好的方法?

java - 在 Objective-C Mac 应用程序中使用 Java 库,并将该应用程序放到 Mac App Store

java - JBoss 5.1 中的异步数据库更新

Android 自定义 View 应该扩展 AppCompatTextView

android - 如何使用 Eclipse 将 Asp.net mvc 3 移动 Web 应用程序转换为 Android 应用程序?

C# 将字节数组 append 到现有文件