java - 如何使用 indexOf() 函数查找具有特定属性的对象
问题描述
我有一个对象 Pet,其中一个功能是检索它的名称。
public class pet{
private String petName;
private int petAge;
public pet(String name, int age){
petName = name;
petAge = age;
}
public String getName(){
return petName;
}
public int getAge(){
return petAge;
}
}
然后我有一个 ArrayList ,其中包含一组宠物,如下面的代码所示:
import java.util.ArrayList;
pet Dog = new pet("Orio", 2);
pet Cat = new pet("Kathy", 4);
pet Lion = new pet("Usumba", 6);
ArrayList<pet> pets = new ArrayList<>();
pets.add(Dog);
pets.add(Cat);
pets.add(Lion;
我想知道如何检索 ArrayList 中的索引或具有我需要的名称的对象。所以如果我想知道乌松巴的年龄,我会怎么做呢?
注意:这不是我的实际代码,它只是用来更好地解释我的问题。
编辑 1
到目前为止,我有以下内容,但我想知道是否有更好或更有效的方法
public int getPetAge(String petName){
int petAge= 0;
for (pet currentPet : pets) {
if (currentPet.getName() == petName){
petAge = currentPet.getAge();
break;
}
}
return petAge;
}
解决方案
您不能将indexOf()
其用于此目的,除非您滥用该equals()
方法的目的。
对从列表长度迭代到列表长度的变量使用for
循环。int
0
在循环内部,比较第 i 个元素的名称,如果它等于您的搜索词,则您已经找到它。
像这样的东西:
int index = -1;
for (int i = 0; i < pets.length; i++) {
if (pets.get(i).getName().equals(searchName)) {
index = i;
break;
}
}
// index now holds the found index, or -1 if not found
如果只想查找对象,则不需要索引:
pet found = null;
for (pet p : pets) {
if (p.getName().equals(searchName)) {
found = p;
break;
}
}
// found is now something or null if not found
推荐阅读
- regression - 如何在 LightGBM 回归中使用叶子的中位数而不是均值
- vb.net - 如何将登录按钮与mysql数据库连接
- reactjs - 反应:dropzone autoprocessqueue() / mount 问题
- javascript - 插入 HTML 时如何使用 express include?
- .net - VB.Net OleDb 连接到以前的源
- java - 发送邮件时偶尔出现“系统找不到指定的路径”异常
- jquery - 如何在 jquery 中获取 translateY (x) 中的值?
- java - Maven mvn exec:java 在 Windows 但不是 Ubuntu 20 上工作
- javascript - 如何在回调中结合setTimeout函数实现回调中的回调?
- javascript - 为什么我的 javascript 代码中的“建筑物”不是函数?