To access an attribute of an object stored in an ArrayList
in Java, you can use the get
method of the ArrayList
class to retrieve the object, and then use the dot notation (.) to access the attribute of the object.
Here is an example of how you can access an attribute of an object stored in an ArrayList
in Java:
ArrayList<Person> persons = new ArrayList<>(); // Add some Person objects to the ArrayList persons.add(new Person("Alice", 25)); persons.add(new Person("Bob", 30)); persons.add(new Person("Charlie", 35)); // Access the name attribute of the second Person object String name = persons.get(1).getName(); // Print the name System.out.println(name); // Output: Bob
In this example, the ArrayList
called persons
contains Person
objects. The Person
class has a getName
method that returns the name of the person.
To access the name attribute of the second Person
object in the ArrayList
, we use the get
method of the ArrayList
to retrieve the object, and then use the dot notation (.) to access the getName
method of the object.
It is important to note that the ArrayList
index is zero-based, which means that the first element of the ArrayList
is at index 0, the second element is at index 1, and so on.
Therefore, to access the second element of the ArrayList
, you need to use the index 1.
It is also important to note that the get
method of the ArrayList
class throws an IndexOutOfBoundsException
if the index is out of range (less than 0 or greater than or equal to the size of the ArrayList
).
Therefore, it is recommended to check the index before accessing an element of the ArrayList
.