java - 如何遍历所有相同类型的对象?
问题描述
对于一个项目,我想检查 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
要循环的项目的情况下执行此操作,而只需查看有多少项目并在创建时循环?
解决方案
要遍历对象,您必须首先将它们放入数组中,如下所示:
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
方法,否则您无法直接将其与您的对象进行比较。相反,您必须比较所需的属性。
推荐阅读
- python - Python 3.6:如何在存在列表和插入方法的情况下构建此函数
- sql - 更改为解码或
- javascript - 如何防止组件在获取数据之前渲染子组件
- android - nativescript-mapbox 显示黑色地图标记
- python - 运行python时如何简化Visual Studio代码中的输出路径
- vba - VBA按换行符拆分数据
- c++ - 在 C++ 中使用 initializer_list 进行结构赋值
- python - 如何在 python 3 中使用翻译表重命名文件以及我在这里犯了什么错误
- python - Python MySQL:使用默认值选择
- javascript - C# 本地函数与 JavaScript 嵌套函数有什么区别?