In my continuing education on Arrays and ArrayLists I'm trying to smarten up my code by passing an ArrayList from one method to another. Here is my code:
public void exampleArrayList () {
ArrayList<String> al = new ArrayList<String>();
al.add("AZ");
al.add("BY");
al.add("CX");
al.add("DW");
al.add("EV");
al.add("FU");
al.add("GT");
display(al);
}
public void display(ArrayList al) {
System.out.println("Index of 'AZ': " + al.indexOf("AZ"));
System.out.println("Index of 'FU': " + al.indexOf("FU"));
System.out.println("Index of 'AA': " + al.indexOf("AA"));
System.out.println("Index of 'CX': " + al.indexOf("CX"));
// for (String row : al)
// System.out.println("Value at Index " + al.indexOf(row) +
// " is " + al.get(al.indexOf(row)));
for(int i = 0; i < al.size(); i++)
System.out.println("Value at Index " + al.indexOf(i) +
" is " + al.get(al.indexOf(i)));
}
In the display method works with both for statements commented out. The for statement that is currently commented out doesn't work because row is looking for a String but get's assigned an object even although array al is a string. Do I need to cast al into a string or something? This is not the case when I run the for loop when the loop is in the same method that created the ArrayList in and I don't understand the difference.
The second for statement that isn't commented out causes a crash giving me the following runtime error:
java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
I tried changing the i < al.size()
to a hard coded number and it still failed and I don't know why.