I have the following arraylist
ArrayList<AnotherClass> exmapleName = new ArrayList<AnotherClass>();
// AnotherClass is a class I created, I store objects of the class in this array, the code to this doesn't matter this works.
Inside of exampleName I have different types of data
public AnotherClass (String someString, int someInt, int anotherInt, int[] intArray, ArrayList<Integer> arrayList)
//Header of the constructor
Now what I need to do is access and store arrayList[0]. But I need to do it once the object has been created so there is actually something inside arrayList.
This is what I've tried but doesn't seem to work
public static void main(String[] args) {
TestClass obj = new TestClass();
obj.read(); //reads file
testMethod();
}
public void testMethod(){
AnotherClass test1 = exampleName.get(1);
ArrayList<Integer> test2 = test1.arrayList;
int test3 = test2.arrayList[0];
} // I broke it down into separate lines to make it more understandable
compiler errors are as follows
cannot find symbol
int test3 = test2.arrayList[0];
symbol: variable arrayList
location: variable test2 of type ArrayList<Integer>
1 error
1 Answer 1
Change
int test3 = test2.arrayList[0];
to
int test3 = test2.get(0);
You use brackets to access arrays' elements, & the .get method of an ArrayList to access its elements.
answered Dec 24, 2015 at 21:00
Mohammed Aouf Zouag
17.2k4 gold badges44 silver badges68 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
ugCode
Much appreciated it worked, I was so close but so far
ugCode
@ Sparta - You use brackets to access arrays' elements, & the .get method of an ArrayList to access its elements. ----- I thought because I'm trying to access a normal array though you use [ ] why do you have to use get?
Mohammed Aouf Zouag
Well,
test2 is an ArrayList of Integers; so there is no such thing as test2.arrayList. Also, you can't do test2[0].ugCode
ah of course I made a silly mistake, I confused myself with another class of mine thanks for the help
lang-java