【问题标题】:How to loop through all object of the same type?如何遍历所有相同类型的对象?
【发布时间】:2019-01-14 12:05:18
【问题描述】:

对于一个项目,我想检查 String 是否与我的一个对象中的 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,而是只查看有多少项目并在创建时循环?

【问题讨论】:

  • 您需要Item 类中的公共字段或getter 才能获得第一个属性。
  • item.name.equals("some string")
  • 我已经有一个 getter 问题是我不知道如何为 Items 设置一个循环,而不必创建一个可以循环的 ArrayList。
  • 您可以使用流:long count = Stream.of(spotion, mpotion, lpotion).filter(item -> item.name.equals(s)).count()

标签: java object


【解决方案1】:

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

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 方法。相反,您必须比较所需的属性。

【讨论】:

  • 附带说明:当直接将数组实例化和分配给变量时,new Item[] 可以省略,否则一个很好的答案 +1 :)
猜你喜欢
  • 1970-01-01
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-13
  • 2022-11-03
  • 1970-01-01
  • 2013-11-04
相关资源
最近更新 更多