javaarraylistindexof

How can I use the indexOf() function to find an object with a certain property


I have an object, Pet, and one of the functions is to retrieve its name.

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;
    }

}

I then have an ArrayList which holds a collection of pets as shown in the code below:

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;

I was wondering how I could retrieve the index in the ArrayList or the object that has the name I need. So if I wanted to find out how old Usumba was, how would I do this?

Note: This is not my actual piece of code, it's just used so that I can better explain my problem.

Edit 1

So far, I have the following but I was wondering if there was a better or more efficient way

public int getPetAge(String petName){
    int petAge= 0;

    for (pet currentPet : pets) {
        if (currentPet.getName() == petName){
            petAge = currentPet.getAge();
            break;
        }
    }

    return petAge;
}

Solution

  • You can't use indexOf() for this purpose, unless you abuse the purpose of the equals() method.

    Use a for loop over an int variable that iterates from 0 to the length of the List.

    Inside the loop, compare the name if the ith element, and if it's equal to you search term, you've found it.

    Something like this:

    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
    

    If you just want to find the object, you don't need the index:

    pet found = null;
    for (pet p : pets) {
        if (p.getName().equals(searchName)) {
            found = p;
            break;
        }
    }
    
    // found is now something or null if not found