user3542837 user3542837 - 3 months ago 20
Java Question

How do i iterate through this arraylist

I'm relatively new to programming. I'm trying to teach myself Java, and I'm messing around with

ArrayLists
. How do I go about printing each of these strings individually? Right now, I have it where it prints each list, but I want to be able to work with each string individually. Like if I wanted to print out the length of each string using a for loop how would I do that? I tried doing the standard for loop, but I couldn't figure out what to put for the termination requirement. I tried
i < 2
since
test[3]
is length 2, but that gave an out of bounds error since the other test lists only have one element.

public static void main(String[] args)
{
int arrlen = 4;
ArrayList[] test = new ArrayList[arrlen];

for(int i=0; i<arrlen; i++)
{
test[i] = new ArrayList<String>();
}

test[0].add("zero");
test[1].add("one");
test[2].add("two");
test[3].add("three");
test[3].add("second three");


for(ArrayList i : test)
{
System.out.println(i);
}

}

Answer

Do:

  for(ArrayList<String> arrayList : test)
  {
    for(String s: arrayList) {
        System.out.println(s);
    }
  }

Or,

  for(ArrayList<String> arrayList : test)
  {
    for(int t = 0; t < arrayList.size(); t++) {
        System.out.println(arrayList.get(t));
    }
  }
Comments