首页 > 解决方案 > 如何遍历所有相同类型的对象?

问题描述

对于一个项目,我想检查 aString是否与我的一个对象中的属性相同String

例如,我有 3 个项目对象:

Item spotion = new Item("small potion", 5, 0, 0, 0, 0, 0);
Item mpotion = new Item("medium potion", 20, 0, 0, 0, 0, 0);
Item lpotion = new Item("large potion", 35, 0, 0, 0, 0, 0);

然后我想检查一下

String s = spotion;

将等于任何 的Item名称(第一个属性);

是否有任何方法可以在不创建ArrayList要循环的项目的情况下执行此操作,而只需查看有多少项目并在创建时循环?

标签: javaobject

解决方案


要遍历对象,您必须首先将它们放入数组中,如下所示:

Item[] items = new Item[] {
    new Item("small potion", 5, 0, 0, 0, 0, 0),
    new Item("medium potion", 20, 0, 0, 0, 0, 0),
    new Item("large potion", 35, 0, 0, 0, 0, 0),
}

然后您就可以使用普通的旧for循环遍历数组:

for(int i = 0; i < items.length; i++){
    //your code here
}

或增强的 for 循环:

for(Item item : items){
    //your code here
}

要比较变量,您只需使用以下方法比较适当的变量equals

if(item.yourVariable.equals(string)){
    //your code here
}

String除非您覆盖其toString方法,否则您无法直接将其与您的对象进行比较。相反,您必须比较所需的属性。


推荐阅读