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);
System.out.println(tempTest.value);
Test tTest = (Test) list.get(1);
System.out.println(tTest.value);
}
}
I used a arrayList because I needed to loop thru the structure, and access specific index locations.