-3

I am new to Java. I have created an arraylist of objects of custom class. Objects of the class contain private variables like firstName, lastName, etc. and public getters and setters to access it and set it.

I wanted to loop through the arraylist to check if firstName in any of the objects in the indexes of arraylist matches the name entered by user. How do I check that?

I know that the get(i) method when used on arraylist returns the element in the specific index. But I don’t want the complete object. I want the variable inside the object.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
AYtech
  • 1
  • 1

1 Answers1

0

You can use get(i) to get the whole object, and then append to that the getter of the attribute that you want. list.get(i).getLastName() for instance.

class Person {
    private String firstName;
    private String lastName;

    public String getLastName() { return this.lastName; }

    // ... etc ...
}

public static void main(String[] args) {
    ArrayList<Person> list = new ArrayList<>();
    list.add(new Person("Jim",       "Hawkins"));
    list.add(new Person("Alexander", "Smollet"));
    list.add(new Person("David",     "Livesy"));

    for (int i = 0; i < list.size(); i++) {
        if (list.get(i).getLastName().equals("Livesy")) { // <-----
            System.out.println("Found matching name at index " + i);
        }
    }
}
Sander
  • 325
  • 2
  • 8