首页 > 解决方案 > 如何使用 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;
}

标签: javaarraylistindexof

解决方案


您不能将indexOf()其用于此目的,除非您滥用该equals()方法的目的。

对从列表长度迭代到列表长度的变量使用for循环。int0

在循环内部,比较第 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

推荐阅读