我正在开发一款游戏,玩家可以获取/制作某种具有特定值(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/