user3137110 user3137110 - 2 years ago 81
Java Question

Accessing methods of objects stored in an ArrayList in Java

I am trying to access methods and values of an object in a ArrayList. I have a system that works but an wondering if there is a better way of doing it. I have simplified the code to illustrate what I am doing. In the real code I will have hundreds of "Test" objects and would be able to loop through them by passing the index to the list.get() method. I feel there should be a better way of accessing the methods than creating a temporary Test object to get to them.

Something like:

list.the object at the list's index.theObjectsMethod(pass a value)

Instead of what I did:

import java.util.ArrayList;

public class Test {
static ArrayList<Object> list = new ArrayList<>();
private int index;
private int value;

public Test(int index, int value) {
this.index = index;
this.value = value;
public int add(int x, int y) {
value = x + y;
return value;
public int subtract(int x, int y) {
return x - y;

public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
Test theTest = new Test(i, i + 1);
list.add(i, theTest);
* my way of accessing the methods
Test tempTest = (Test) list.get(0);
tempTest.add(12, 1);
Test tTest = (Test) list.get(1);

I used a arrayList because I needed to loop thru the structure, and access specific index locations.

Answer Source

You have created a List of Object. Therefore, any iteration will only provide access to the methods of the Object class. You can:

  1. Change the List declaration to List<Test> list = new ArrayList<>();

This approach would allow you to access the value without casing it as in the code you posted. For example:

for (Test test : list) {
  test.add(1, 2);


Test t = list.get(0);  //though watch out for empty list, etc.
t.subtract(2, 1);
  1. You can continue to cast your retrieval, but it is not an optimal approach.

As an aside, when adding to a list the default it to append, so you can simply do something like to add to the list.

for (int i = 0; i < 5; ++i) {
  Test t = new Test(i, i+1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download