Reputation: 99
I seem to be having trouble in the logic of my problem. What I am trying to do is have a List of Arrays. Each Array contains 2 String.
I am trying to iterate through my List and then printing the elements of the arrays. I seem to get stuck in printing the first Array (which is what my code does), though I am stuck in the logic.
public static void main(String[] args) {
List<List<String>> addresses = new ArrayList<List<String>>();
ArrayList<String> singleAddress1 = new ArrayList<String>();
singleAddress1.add("17 Fake Street");
singleAddress1.add("18 Fake Street");
ArrayList<String> singleAddress2 = new ArrayList<String>();
singleAddress2.add("Phoney town");
singleAddress2.add("not real town");
ArrayList<String> singleAddress3 = new ArrayList<String>();
singleAddress3.add("sillyname town");
singleAddress3.add("alsosilly town");
addresses.add(singleAddress1);
addresses.add(singleAddress2);
addresses.add(singleAddress3);
System.out.print("Original contents of al: " + addresses + "\n");
Iterator itr = addresses.iterator();
while (itr.hasNext()) {
Object element = itr.next();
System.out.print(element + "\n");
for (int i = 0; i < singleAddress1.size(); i++) {
System.out.println(singleAddress1.get(i));
}
itr.remove();
}
}
}
Upvotes: 0
Views: 190
Reputation: 37083
Whilst you are iterating over the outer array list addresses
, internally you end up iterating on same singleAddress1
instead of all the list elements which you would get from iterator using for (int i = 0; i < singleAddress1.size(); i++) {
.
Your iteration loop should be:
Iterator<List<String>> itr = addresses.iterator();
while (itr.hasNext()) {
List<String> element = itr.next();
^^^^^^^^^^^^
System.out.print(element + "\n");
for (int i = 0; i < element.size(); i++) {
^^^^^^^^
System.out.println(element.get(i));
}
itr.remove();
}
Upvotes: 2
Reputation: 6114
Why don't you use a simple for-each
loop:
for(List<String> list:addresses)
{
for(String str:list)
{
System.out.println(str);
}
}
Upvotes: 1